Using memory pools

How can i use memory pool with a char array?

Is there a way to allocate memory somewhere in the middle of the array?
i.e. allocate memory in chunks.
eg. allocate 24 bytes at location arr[56] in 256 byte array.

Similarly how can i deallocate that memory?

Any help is appreciated.

Thnx!
No standard library method of doing that. You certainly can write your own functions to do so. This might help get you started:
1
2
3
4
5
6
7
8
class Chunk
{ const int size = 256;  // fixed size of character array
   char m_mem[size];   // memory being allocated
   bitset<size> m_bits;  // bit array to keep track of what's allocated
public:
    char * Allocate (int nbytes);
    void Release (char * mem, int nbytes);
};


AbstractionAnon wrote:
No standard library method of doing that.
That's not entirely true. std::allocator is used for allocating memory. Not exactly like the OP wants, but it can be done.

Just a rough idea:
1
2
3
4
5
6
std::allocator<unsigned char> alloc;
unsigned char *ptr = alloc.allocate(256) //allocate space for 256 chars (chars are 1 byte in size). 
//returns a pointer to the location of the first allocated memory space.

//deallocate
alloc.deallocate(ptr, 256);


Read up on std::allocator here:
http://www.cplusplus.com/reference/memory/allocator/?kw=allocator
Thanks. Is the use of memory pools only to save system calls like malloc/new, because otherwise the memory is always going to get allocated in chunks like you mentioned above:

char * Allocate (int nbytes);

and for releasing that memory, i will have to keep track of what sized chunk was allocated and the pointer to that location:

void Release (char * mem, int nbytes);

So if i allocate memory multiple times and deallocate it separately, how do i keep track of the chunk size every time? Do i have to save that data in some object, like obj.ptr and obj.dataSize?
Boost includes a pool

Boost.Pool - 1.53.0
http://www.boost.org/doc/libs/1_53_0/libs/pool/doc/html/index.html

Andy
mukuladbagiri wrote:
Do i have to save that data in some object
That's correct. You're responsible for keeping track of how much you've allocated.

@andywestken
I didn't know boost had that. Awesome :D
Thanks for the answers. On similar lines, i was curious to know if there is a way to avoid fragmentation if memory is allocated and deallocated frequently. Right now I am using best fit technique to allocate memory. ie. i look for smallest memory block available in the pool, but it still leaves holes in the pool.

Thnx,
Mukul
Hmmm... maybe it's too involved a question for here?

But there is quite a bit about the web, if you search for "how to design a low fragmentation heap", "heap allocation strategies", and the like.

While I'm here, this article might be of interest?

A short puzzle about heap expansion
http://blogs.msdn.com/b/oldnewthing/archive/2010/04/29/10004218.aspx

Andy
Topic archived. No new replies allowed.