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

Resetting an arena in one step

Resetting an arena in one step

What you'll learn: How to efficiently clear all memory allocated within an arena by simply moving a single pointer.

The "Endless Notepad" Analogy

Imagine you are a waiter taking orders on a long notepad. Instead of using a separate piece of paper for every customer, you write each order one after another. To keep track of where you are, you keep your thumb on the spot where the blank page begins.

When the shift is over and all the customers have left, you don't need to go back and erase every single line with an eraser. You simply move your thumb back to the very top of the first page. Even though the old writing is technically still there, the notepad is now "empty" because you are ready to write over it.

Moving the Offset

In arena allocation, we manage a large, pre-allocated block of memory. We use a variable (often called an offset or top) to track how many bytes we have used. Every time we "allocate" memory, we just move that pointer forward.

To free all that memory at once, we don't call free() on every individual object. Instead, we reset the offset back to zero.

#include <stddef.h>
#include <stdint.h>

typedef struct {
    size_t size;
    size_t offset;
    uint8_t *buffer;
} Arena;

// To "free" everything, we just reset the offset
void arena_reset(Arena *arena) {
    arena->offset = 0;
}

// Example usage
int main() {
    Arena my_arena = { .size = 1024, .offset = 0, .buffer = some_preallocated_mem };

    // Allocate 100 things...
    // ...

    // Instead of 100 free() calls, we do this:
    arena_reset(&my_arena); 
    
    // The arena is now ready to be reused immediately.
    return 0;
}

Why this is powerful

In standard C, if you allocate 1,000 small nodes for a linked list, you have to call free() 1,000 times. This is slow and prone to "memory leaks" if you forget even one.

With an arena, the arena_reset function is a "constant time" operation. Whether you have one object or one million objects inside the arena, resetting it takes the exact same amount of time: the time it takes to set an integer to zero. This makes arenas incredibly fast for tasks that happen in cycles, like a frame in a video game or a single request in a web server.

Key takeaway

Resetting an arena is as simple as setting its offset back to zero, instantly "freeing" all contained data without expensive cleanup loops.