Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement own memory pool

Tags:

I want to allocate a certain amount of memory upfront and use that memory for the rest of the program. The program will basically be allocating memory for a few strings and structs. How do I implement this? What data structures are used to store the pointers and how do I use it to give me a specific amount?

For example, if I malloc 1 MB of space and have it in a pointer p, how do I carve out a 250 KB piece from it ?

This is just meant to be a quick and dirty implementation.

like image 527
DavidL Avatar asked Jul 31 '12 21:07

DavidL


1 Answers

If you want to be able to return memory to the pool, it gets more complicated. However, for the quick and not-quite-so-dirty approach, you may want to implement some code that you can use again...

typedef struct pool
{
  char * next;
  char * end;
} POOL;

POOL * pool_create( size_t size ) {
    POOL * p = (POOL*)malloc( size + sizeof(POOL) );
    p->next = (char*)&p[1];
    p->end = p->next + size;
    return p;
}

void pool_destroy( POOL *p ) {
    free(p);
}

size_t pool_available( POOL *p ) {
    return p->end - p->next;
}

void * pool_alloc( POOL *p, size_t size ) {
    if( pool_available(p) < size ) return NULL;
    void *mem = (void*)p->next;
    p->next += size;
    return mem;
}

In my experience, when using pools like this to allocate many objects, I want to precalculate how much memory will be needed so that I'm not wasteful, but I also don't want to make any mistakes (like not allocating enoudh). So I put all the allocation code inside a loop, and set up my pool allocation functions to accept a flag that performs a 'dummy' allocation on an empty pool. The second time around the loop, I have already calculated the size of the pool so I can create the pool and do the real allocations all with the same function calls and no duplicate code. You'd need to change my suggested pool code, because you can't do this with pointer arithmetic if the memory hasn't been allocated.

like image 138
paddy Avatar answered Oct 12 '22 11:10

paddy