Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/where is sbrk used within malloc.c?

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??)

like image 756
user997112 Avatar asked Dec 31 '13 21:12

user997112


People also ask

What is sbrk() in C?

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.

What does sbrk 0 do?

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().

What is brk memory?

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.

What is program break?

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.


1 Answers

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.

like image 165
interjay Avatar answered Sep 22 '22 16:09

interjay