patterncMinor
Simple memory pool using no extra memory
Viewed 0 times
simpleusingmemorypoolextra
Problem
I've borrowed the idea from the internet and I would like to know if my implementation is all right and what could be improved.
It uses the free memory to store links to each node, so there's no extra memory being used.
It uses the free memory to store links to each node, so there's no extra memory being used.
memory_pool.h#ifndef MEMORY_POOL_H
#define MEMORY_POOL_H
#include
#define MEMORY_POOL_SUCCESS 1
#define MEMORY_POOL_ERROR 0
#define MEMORY_POOL_MINIMUM_SIZE sizeof(void *)
typedef struct {
void **head;
void *memory;
} Memory_Pool;
//size must be greater than or equal to MEMORY_POOL_MINIMUM_SIZE
int mp_init(Memory_Pool *mp, size_t size, size_t slots);
void mp_destroy(Memory_Pool *mp);
void *mp_get(Memory_Pool *mp);
void mp_release(Memory_Pool *mp, void *mem);
#endifmemory_pool.c#include "memory_pool.h"
int mp_init(Memory_Pool *mp, size_t size, size_t slots)
{
//allocate memory
if((mp->memory = malloc(size * slots)) == NULL)
return MEMORY_POOL_ERROR;
//initialize
mp->head = NULL;
//add every slot to the list
char *end = (char *)mp->memory + size * slots;
for(char *ite = mp->memory; ite memory);
}
void *mp_get(Memory_Pool *mp)
{
if(mp->head == NULL)
return NULL;
//store first address
void *temp = mp->head;
//link one past it
mp->head = *mp->head;
//return the first address
return temp;
}
void mp_release(Memory_Pool *mp, void *mem)
{
//store first address
void *temp = mp->head;
//link new node
mp->head = mem;
//link to the list from new node
*mp->head = temp;
}Solution
I see a few things that might be changed.
First, consider checking the passed
The initialization is more complex than it needs to be. Rather than make repeated calls to
Within
In
mp_initFirst, consider checking the passed
*mp variable to see if it's NULL at least within the mp_init call. Alternatively, you could also allocate that structure within the mp_init routine and return a pointer to it or NULL on error.The initialization is more complex than it needs to be. Rather than make repeated calls to
mp_release and do all of that pointer manipulation, you could use this:char *ptr;
for (ptr = mp->memory; --slots; ptr+=size)
*(void **)ptr = ptr+size;
*(void **)ptr = NULL;
mp->head = mp->memory;mp_releaseWithin
mp_release, there is no error checking. This might be OK if we're looking for extreme performance, but it might be nice to have at least a debug version that checks that mem actually points to a slot. For that to work, of course, you'll have to add at least one more variable to the structure to contain the size parameter.mp_destroyIn
mp_destroy it might be prudent to set mp->head = NULL so that any subsequent mp_get attempts will fail.Code Snippets
char *ptr;
for (ptr = mp->memory; --slots; ptr+=size)
*(void **)ptr = ptr+size;
*(void **)ptr = NULL;
mp->head = mp->memory;Context
StackExchange Code Review Q#48919, answer score: 7
Revisions (0)
No revisions yet.