Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Memory and sbrk

On a 32 bit Linux system, a process can access up to 4 GB of virtual address space; however, processes seem to be conservative in varying degrees in reserving any of that. So a program that uses malloc will occasionally grow its data segment by a syscall sbrk/brk. Even those pages aren't claimed in physical memory yet. What I don't fully understand is why we need to sbrk in the first place, why not just give me 4 GB address space avoiding any sbrk call, as until we touch/claim those blocks, it is essentially a free operation right?

like image 935
Mâtt Frëëman Avatar asked Apr 25 '12 09:04

Mâtt Frëëman


People also ask

What does brk and sbrk do?

The brk() and sbrk() functions are used to change the amount of space allocated for the calling process. The change is made by resetting the process' break value and allocating the appropriate amount of space. The amount of allocated space increases as the break value increases. The newly-allocated space is set to 0.

How does malloc use sbrk?

Malloc is a function provided by the C standard library which is used to dynamically allocate memory. It uses a low-level memory management function, called sbrk, to determine if the heap has available space. Silicon Labs provides a simple implementation of sbrk, designed for compatibility between all projects.

What is brk and sbrk system calls?

brk and sbrk are basic memory management system calls used in Unix and Unix-like operating systems to control the amount of memory allocated to the data segment of the process. These functions are typically called from a higher-level memory management library function such as malloc.

Does malloc grow the heap?

The system call sbrk() is used to increase the size of the data section, all right. Usually, you will not call it directly, but it will be called by the implementation of malloc() to increase the memory available for the heap. The function malloc() does not allocate memory from the OS.


1 Answers

What happens if you memory-map a file (a very common thing to do under Linux)? It has to go somewhere in the address space, so there must be some means of defining "used" and "not used" parts.
Shared memory (which is really just mapping a file without an actual file) is the same. It has to go somewhere, and the OS must be sure it can place it without overwriting something.

Also, it is preferrable to maintain locality of reference for obvious (and less obvious) efficiency reasons. If you were allowed to just write to and read from any location in your address space, you can bet that some people would do just that.

like image 194
Damon Avatar answered Nov 15 '22 07:11

Damon