Example #1
0
/**
 * @brief  Allocate a variable sized object on the memory pool.
 * @param  pool The pool to allocate from.
 * @param  size The size of the object to allocate.
 * @return A valid address on success, NULL on failure.
 */
void *lpx_mempool_variable_alloc(lpx_mempool_variable_t *pool, long size)
{
    void *candidateBlock = NULL;
    int unlockNeeded = 0;
    
    if (UNLIKELY(pool == NULL)) {
        return NULL;
    }

    // Lock the mutex if needed.
    if (pool->poolMutex != NULL) {
        if (0 != pthread_mutex_lock(pool->poolMutex)) {
	    return NULL;
	}
	unlockNeeded = 1;
    }

    // First off, adjust the size to accomodate the metadata.
    size += MEMPOOL_PER_BLOCK_OVERHEAD;
    if (size < 3 * sizeof(long)) {
        // Because this should be linkable back into the list.
	size += 3 * sizeof(long);
    }

    // Find the first fit block from the free list.
    candidateBlock = findFirstFit(pool, size);
    if (candidateBlock == NULL) {
        if (unlockNeeded) {
	    pthread_mutex_unlock(pool->poolMutex);
	}
        return NULL;
    }
    
    // Split the block and re-link the free list.
    candidateBlock = splitBlock(pool, candidateBlock, &size);
    if (candidateBlock == NULL) {
        if (unlockNeeded) {
	    pthread_mutex_lock(pool->poolMutex);
	}
	return NULL;
    }

    // Prep the block for return.
    ((long *)candidateBlock)[0] = (long)pool;
    ((long *)candidateBlock)[1] = size;

    // Unlock the mutex if needed.
    if (pool->poolMutex != NULL) {
        if (0 != pthread_mutex_unlock(pool->poolMutex)) {
	    return NULL;
	}
    }

    // &candidateBlock[2] is the start of the user memory block.
    return &(((long *)candidateBlock)[2]);
}
void *my_malloc(size_t size)
{
    freeBlockHotfix();

    if(size == 0)
    {
        return NULL;
    }

    else if(size < 0)
    {
        return (void *) -1;
    }

    else
    {
        return findFirstFit(size);
    }
}