Quote:
Originally Posted by hda7
more along the lines of how an example malloc implementation would acquire memory.
|
I looked at an implementation of malloc Yesterday before making the obvious suggestion that the way to find out how malloc is implemented is to look at the open source code.
I didn't post that suggestion, because malloc actually buries its acquisition of memory so deep in macros and conditionals that it is incomprehensible. That is a consequence of writing efficient portable code across multiple OS's where specific efficient methods would not be portable.
Malloc in Linux appears to ultimately used a mixture of sbrk and mmap for acquiring memory from the kernel.
mmap seems to be clearly documented and is a fairly effective method by itself for acquiring memory from the Linux kernel. Depending on your specific needs, understanding and using mmap may be enough.
sbrk is simple, efficient, and understandable in the cases where there is free virtual address space for contiguous growth of the process's original contiguous heap. I find the documentation confusing and even contradictory for the case where some loaded .so file or other
mmaped region prevents contiguous expansion of the original heap. Does sbrk then simply fail or does it deliver noncontiguous memory, or what?
I was expecting someone who knew these answers to reply sooner. But as that hasn't happened, you have my partial answers:
Use mmap if that is good enough.
Research sbrk, to learn more than I learned, if mmap alone isn't enough for you.
Dig deeper than I did into the source code of malloc, if reading mmap and sbrk documentation isn't enough.