Reputation: 312
Is there any malloc/realloc/free like implementation where i can specify a memory region where to manage the memory allocation?
I mean regular malloc (etc.) functions manages only the heap memory region. What if I need to allocate some space in a shared memory segment or in a memory mapped file?
Upvotes: 1
Views: 1958
Reputation: 11
I asked myself this question recently too, because I wanted a malloc implementation for my security programs which could safely wipe out a static memory region just before exit (which contains sensitive data like encryption keys, passwords and other such data).
First, I found this. I thought it could be very good for my purpose, but I really could not understand it's code completely. The license status was also unclear, as it is very important for one of my projects too.
I ended up writing my own. My own implementation supports multiple heaps at same time, operating over them with pool descriptor structure, automatic memory zeroing of freed blocks, undefined behavior and OOM handlers, getting exact usable size of allocated objects and testing that pointer is still allocated, which is very sufficient for me. It's not very fast and it is more educational grade rather than professional one, but I wanted one in a hurry.
Note that it does not (yet) knows about alignment requirements, but at least it returns an address suitable for storing an 32 bit integer.
Upvotes: 1
Reputation: 1464
Not 100 %, As per your question you want to maintain your own memory region. so you need to go for your own my_malloc
, my_realloc
and my_free
Implementing your own
my_malloc
may help youvoid* my_malloc(int size) { char* ptr = malloc(size+sizeof(int)); memcpy(ptr, &size, sizeof(int)); return ptr+sizeof(int); }
This is just a small idea, full implementation will take you to the answer.
use the same method to achieve my_realloc
and my_free
Upvotes: 1
Reputation: 6563
It is not very hard to implement your own my_alloc
and my_free
and use preferred memory range. It is simple chain of: block size, flag free/in use, and block data plus final-block marker (e.g. block size = 0). In the beginning you have one large free block and know its address. Note that my_alloc
returns the address of block data and block size/flag are few bytes before.
Upvotes: 0
Reputation: 325
Iam using Tasking and I can store data in a specific space of memory. For example I can use:
testVar _at(0x200000);
I'm not sure if this is what you are looking for, but for example I'am using it to store data to external RAM. But as far as I know, it's only workin for global variables.
Upvotes: 0