I want to initialize a memory region and thus can use malloc
(in glibc) to allocate memory only from this region. There will be multiple malloc
used and every malloc
operation should only use this pre-defined region. This region requires contiguous memory addresses with a specific size.
My thought is to create a region_init
function that uses sbrk
or shared memory object (using shm_open
?) to initialize a memory region that can be used by (multiple) malloc
. BTW, I think mmap()
doesn't work for this scenario because mmap()
doesn't always return contiguous addresses. The problem is that I don't know how to make every malloc
use this memory region I created (using sbrk
? shared memory? and/or others?). Can I achieve this by modifying the source codes of malloc
in glibc
? If I can, how to modify glibc (any idea is appreciated)? What should I do for implementing this functionality?
Before this question, I asked a related question on StackOverflow. In the previous question, some answer/comment suggested that I can use a single malloc to allocate a large memory buffer/region and implement my own API to manage this memory (e.g., m_malloc
to allocate part of the memory from this memory buffer/region). However, the problem of this design is that it is hard to free
especially when there are multiple variables in this region. The free
in glibc can only free the whole region that is malloc'd. If I want to free a variable (when there are many variables in this malloc'd region), I can only free the whole region which means all of the variables are freed. I really want to use free
to free the memory of any variable I allocated in the memory region created by only one malloc
.
I hope my question is clear. Thanks for your help and ideas.