Search code examples
c++mallocsbrk

How does sbrk() work in C++?


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


Solution

  • 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.