Is heap memory in Linux contiguous?

47 views Asked by At

I was looking at the man page for brk(2), and it said that it increases the program break therefore allocating more memory to the heap. However, the way that I understand it, heap memory isn't always completely virtually contiguous in the PROG_TEXT -> PROG_HEAP (prog break) -> PROG_STACK manner that it seems to describe. Is the program heap actually virtually contiguous? If not, how does brk(2) work in a way that's consistent with what's described on the man page?

1

There are 1 answers

1
Joshua On

Heap memory may or may not be contiguous.

  1. malloc() is not restricted to sbrk() (sbrk() is what calls brk()...) The standard mode is the small heap comes from brk() and the big heap comes from mmap(); you are not expected to care about this as a user of malloc().
  2. The application may call sbrk() thus fragmenting the heap.

On 64 bit processors there's a pretty good chance of running out of RAM before brk() has to give up and malloc() resorts to mmap(); however this scenario can happen.

Your code really shouldn't care. If you're in a situation that's so degenerate that you care (I was once on 32 bit where I needed almost all my address space for a single workspace) you are whole program constrained and need to turn off ASLR for your process. If that's your question, answer here: https://askubuntu.com/a/1355819/287855