malloc like function using custom heap
What would be the best approach in C if I wish to construct malloc like functionality with a custom pre-allocated heap?
My specific issue here is that I have a mmap-able (memory like) device which has been placed into my address space but I need to attain a more flexible way of using this memory to store objects which will be allocated and freed over time.
I know that malloc, free and the other similar functions are used to perform this kind of allocation on the heap but is there any way to use the logic provided by this kind of function for its dynamic behaviour while providing my own address space to operate as the heap in question?
Boost.Interprocess has stateful allocators suitable for shared memory segments: they may be re-usable for other mmapped address ranges too.
Otherwise, you may need to roll your own. In increasing order of complexity, you could consider:
Which of those are suitable will depend on some information you haven't given:
realloc
malloc
and family is a rather complex set of library functions. They do a lot of bookkeeping like which parts of the heap are in use and such.
A relatively easy way to use the standard memory allocator malloc
is to remap the default heap with your custom mapping.
void * part_of_heap = memalign(sysconf(_SC_PAGESIZE), nbytes);
void * ret = mmap(part_of_heap, nbytes
, PROT_READ | PROT_WRITE, MAP_FIXED, fd, 0);
if (ret == MAP_FAILED) {/* ... */}
free(part_of_heap);
Now anything that is placed in the area part_of_heap
- part_of_heap+nbytes
by malloc will go into your own mapped area. This is unsupported though and will not guarantee that any allocations will actually go there.
Otherwise you would need to implement your own memory allocator, which has to do bookkeeping. A linked list would do for starters. I know of no open implementation that would serve your needs.
链接地址: http://www.djcxy.com/p/82530.html上一篇: c malloc函数回滚
下一篇: malloc像使用自定义堆的函数