Understanding sbrk

medium · memory, syscalls, heap

Understanding sbrk: The Foundation of Heap Allocation

Before you can build malloc, you must understand how to request memory from the operating system.

The Program Break

Every Unix process has a program break - the boundary between the heap and unmapped memory. The sbrk system call manipulates this boundary:

Low addresses                              High addresses
┌────────────────┬──────────────┬─────────────────────────┐
│     Code       │    Stack     │         Heap            │
│    (text)      │      ↓       │           ↑             │
└────────────────┴──────────────┴─────────────────────────┘
                                           ↑
                                    Program Break

sbrk Semantics

void *sbrk(intptr_t increment);
  • sbrk(0) - Returns current program break (doesn't change anything)
  • sbrk(n) - Extends heap by n bytes, returns the previous break (start of new region)
  • sbrk(-n) - Shrinks heap (rarely used - we'll learn why)
  • Returns (void*)-1 on failure (NOT NULL!)

Your Task

Implement a simple heap manager that tracks memory requests:

// Initialize heap manager. Call once at start.
void heap_init(void);

// Request 'size' bytes from OS. Returns pointer to new memory.
// Returns NULL if size is 0 or sbrk fails.
void *heap_request(size_t size);

// Return total bytes requested so far.
size_t heap_total_requested(void);

// Return current program break.
void *heap_current_break(void);

// Return number of sbrk calls made.
int heap_sbrk_count(void);

Critical Thinking

  1. Why does sbrk return (void*)-1 instead of NULL on failure? Think about what address 0 means in the heap context.
  2. Why is sbrk(-n) problematic for a real allocator? Consider: allocate A, B, C then free B. Can you shrink the heap?
  3. What does the return value of sbrk(n) represent? It's the OLD break, which is where your new memory STARTS.

Constraints

  • Do NOT include headers - <unistd.h> is provided
  • Handle sbrk failure correctly (check for (void*)-1)
  • Track statistics accurately
Run tests to see results
No issues detected