Course contentsShow
← C
Lesson 592 of 1,2198. Memory ManagementFree lesson

Introduction to brk and sbrk

Introduction to brk and sbrk

What you'll learn: How the operating system moves the boundaries of your program's memory to give you more room to work.

The Invisible Fence

Imagine your program lives in a fenced-in yard. This yard represents the "Heap"—the area where dynamic memory is stored. When you start your program, the fence is set at a specific location called the program break.

The program break is the address marking the very end of your program's data segment. Anything inside the fence is yours to use; anything outside belongs to the operating system. If your program needs more memory than what is currently inside the fence, it can’t just hop the boundary. It has to ask the operating system to move the fence further out. This is exactly what brk and sbrk do.

Moving the Boundary

These two system calls are the low-level mechanics behind functions like malloc. While malloc is like a manager who organizes your space, brk and sbrk are the construction workers who actually expand the lot.

  • brk(addr): This sets the "fence" to a specific, absolute address.
  • sbrk(increment): This moves the "fence" by a relative amount. If you call sbrk(1024), you are asking the OS to move the fence 1024 bytes further away, growing your heap.

A Conceptual Example

In modern C, you rarely use these directly because malloc handles the complexity for you. However, seeing how they work reveals how memory is "created" out of thin air.

#include <unistd.h>
#include <stdio.h>

int main() {
    // Get the current location of the program break
    void *current_break = sbrk(0);
    printf("Current break: %p\n", current_break);

    // Expand the heap by 4096 bytes (usually one page of memory)
    // sbrk returns the PREVIOUS break address on success
    void *previous_break = sbrk(4096);

    if (previous_break == (void *)-1) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    void *new_break = sbrk(0);
    printf("New break:     %p\n", new_break);

    return 0;
}

Why it matters

When you call sbrk(0), it doesn't move the fence at all; it just tells you where the fence is currently located. When you provide a positive number, the operating system maps new physical memory to your program’s virtual address space. If you provide a negative number, you are actually shrinking the heap and giving memory back to the system.

Key takeaway

The program break is the boundary of your heap, and brk/sbrk are the system-level tools used to push that boundary forward to claim more memory.