c malloc functionality for custom memory region

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?


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 you

void* 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.

Refer this question

use the same method to achieve my_realloc and my_free


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.


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.

链接地址: http://www.djcxy.com/p/80442.html

上一篇: Go怎么没有stackoverflows

下一篇: c自定义内存区域的malloc功能