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.
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<unsignedchar> alloc;
unsignedchar *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);
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?
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.