I have read in Advanced Unix Programming (and also in a few other books) that Linux malloc()
uses the Linux system call sbrk()
to request memory from the operating system.
I am looking at the glibc malloc.c
code and I can see many mentions of sbrk()
in the comments, but not referred to directly in the code.
How/where is sbrk()
referred to/used when malloc()
requests memory from the OS?
(This could be a general misunderstanding on my part of how system calls are made from the C runtime library. If so, I would be interested to know how they are made??)
The sbrk() function is used to change the space allocated for the calling process. The change is made by adding incr bytes to the process's break value and allocating the appropriate amount of space. The amount of allocated space increases when incr is positive and decreases when incr is negative.
If you call sbrk(0), then it returns the current end of the heap. Now, malloc() (and the related programs realloc() and calloc()) all call sbrk() to get the memory to allocate in the heap. They are the only routines that call sbrk(). Thus, the only way that you can get memory in the heap is through malloc() or sbrk().
brk() sets the end of the data segment to the value specified by addr, when that value is reasonable, the system has enough memory, and the process does not exceed its maximum data size (see setrlimit(2)). sbrk() increments the program's data space by increment bytes.
The program break is the address of the first location beyond the current end of the data region. The amount of available space increases as the break value increases.
Glibc's malloc.c requests more memory by calling the function stored in the __morecore
global function pointer (the call actually uses the macro MORECORE
which expands to __morecore
). By default, this holds the address of function __default_morecore
, which is defined in morecore.c. This function calls sbrk
.
Note that some malloc
implementations may use mmap
to get more memory instead of sbrk
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With