Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a heap at a specific memory address for dynamic memory allocation

Is there a way to create a heap at a specific memory location (separate from the system heap) that can be used for dynamic memory allocation, but makes use of the dynamic memory allocator built into the C library.

I'm looking for something functionally equivalent to this:

UserHeap heap(startAddress, size);

void* allocatedMemory1 = heap.Allocate(100);  //Allocate 100 bytes.
void* allocatedMemory2 = heap.Allocate(200);  //Allocate 200 bytes.

/* ... Do seomthing useful with the memory ... */

heap.Free(allocatedMemory1);
heap.Free(allocatedMemory2);

This uheap.h seems to have what I'm looking for, but this doesn't seem to exist in newlib. I'm wondering if GCC or newlib might have something. If not I think I may end up porting ptmalloc. However, its my understanding that this code is already in the C library and I'd hate to waste the memory reproducing it.

I'm using Sourcery Codebench Lite (GCC) with newlib (C library).

like image 387
Verax Avatar asked Dec 04 '25 16:12

Verax


1 Answers

Rolling out your own allocator isn't all that hard and in many ways can be quite instructive. First you need to figure out what sort of allocation/deallocation pattern you want to support in that heap. For general use, allocators similar to dlmalloc (Doug Lea's) are quite good. There are many more kinds for specific usages: stack based (where a free is always the address of the last allocated unfreed memory block), fixed sized based (where the memory is divided in fixed sizes which are returned), queue based, small block, etc.

Most of these can have an internal allocator as well, for example suppose you have a fixed sized allocator, you could tell it to allocates in blocks of X bytes (from a second allocator or from the system) which then get divided in blocks of Y bytes. Pointers to chunks of size Y bytes are returned but when there is no free block, you allocate a new block of size X and divide it up.

For convenience, you can also implement the new/delete operators globally or on certain classes to redirect their allocations to your custom allocator. Placement new on your heap is also handy, see below.

I personally prefer using macros since it allows extra debug information to be added (function/line/etc) quite easily. ie:

#define CUSTOM_NEW(Heap) new(Heap, __FUNCTION__, __LINE__)
int* ptr = CUSTOM_NEW(someHeap) int[32];
like image 95
Nicholas Frechette Avatar answered Dec 07 '25 15:12

Nicholas Frechette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!