Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sbrk() work in C++?

Tags:

c++

malloc

sbrk

Where can I read about sbrk() in some detail?

How does it exactly work?

In what situations would I want to use sbrk() instead of the cumbersome malloc() and new()?

btw, what is the expansion for sbrk()?

like image 562
Lazer Avatar asked Jan 16 '10 07:01

Lazer


People also ask

What is the use of sbrk?

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.

How is sbrk implemented?

On Linux, sbrk() is implemented as a library function that uses the brk() system call, and does some internal bookkeeping so that it can return the old break value.

What is the difference between brk () and sbrk ()?

brk identifies the lowest data segment location not used by the caller as addr . This location is rounded up to the next multiple of the system page size. sbrk , the alternate interface, adds incr bytes to the caller data space and returns a pointer to the start of the new data area.

Is sbrk a system call?

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.


1 Answers

Have a look at the specification for brk/sbrk.

The call basically asks the OS to allocate some more memory for the application by incrementing the previous "break value" by a certain amount. This amount (the first parameter) is the amount of extra memory your application then gets.

Most rudimentary malloc implementations build upon the sbrk system call to get blocks of memory that they split up and track. The mmap function is generally accepted as a better choice (which is why mallocs like dlmalloc support both with an #ifdef).

As for "how it works", an sbrk at its most simplest level could look something like this:

uintptr_t current_break; // Some global variable for your application.
                         // This would probably be properly tracked by the OS for the process
void *sbrk(intptr_t incr)
{
    uintptr_t old_break = current_break;
    current_break += incr;
    return (void*) old_break;
}

Modern operating systems would do far more, such as map pages into the address space and add tracking information for each block of memory allocated.

like image 155
Matthew Iselin Avatar answered Oct 18 '22 09:10

Matthew Iselin