The malloc function uses both sbrk and mmap functions. Now the sbrk function increases or decreases the data segment. So it grows linearly. Now my question is, is this linearity always maintained, or for example, an mmap call can allocate memory overlapping the data segment?
I’m talking about multithreaded programs running on multicore systems. This blog talks about some serious flaws of sbrk for multithreaded programs, and it points out that it is possible that memory allocated with sbrk can be intermingled with memory alloacted with mmap (The sbrk heap could become discontinuous because a mmaped region or a shared object obstructs the growth of the heap).
That blog post doesn’t see the forest for the trees; only the
mallocimplementation is allowed to callsbrkwith a nonzero argument. More precisely, mostmallocimplementations for Unix will stop functioning correctly (and by that I mean “your program will crash”) if application code callssbrkwith a nonzero argument. If you want to make a large allocation directly from the OS you must usemmapto do it.(It is true that in a multi-threaded program,
mallocmust internally wrap a mutex around its calls tosbrk, but that’s an implementation detail. POSIX saysmallocis thread safe, that’s the important thing for an application programmer.)mmapwill not allocate memory overlapping thebrkarea unless you useMAP_FIXED. If you useMAP_FIXEDand your program blows up you get to keep all the pieces.The kernel tries to avoid doing it, but
mmapin normal operation could conceivably allocate memory close to the top of thebrkarea. If this happens, a subsequentsbrkcall that would collide with themmapregion will fail. It will not allocate discontiguous memory. Good implementations ofmallocought to detect this condition and start usingmmapfor everything. I have not actually tried it, but a test program would be pretty easy to write.