Managing a static memory pool
What you'll learn: How to manage memory by carving out chunks from a pre-allocated static array instead of using the heap.
The Buffet Tray Analogy
Standard memory allocation (malloc) is like a waiter bringing individual plates from a distant kitchen. It’s flexible, but it takes time and might fail if the kitchen is messy.
A static memory pool is like a buffet tray already sitting on your table. You’ve reserved a large, fixed square of space at the start of your program. When you need memory, you don't ask the "kitchen" (the OS); you just slice off a piece of that tray. This is incredibly fast and essential for embedded systems where the "heap" might not even exist.
Implementing a Simple Pool
In C, we can create this pool using a large static global array. By using a static array, the memory is allocated when the program starts and stays there until it ends. To manage it, we keep track of an "offset"—a marker that tells us where the next free byte begins.
#include <stdio.h>
#define POOL_SIZE 1024
static char memory_pool[POOL_SIZE];
static size_t next_free_byte = 0;
void* pool_alloc(size_t size) {
// Check if we have enough room left
if (next_free_byte + size > POOL_SIZE) {
return NULL; // Out of memory!
}
// Get the address of the next available spot
void* allocated_ptr = &memory_pool[next_free_byte];
// Move the marker forward for the next request
next_free_byte += size;
return allocated_ptr;
}
int main() {
// Grab space for an array of 10 integers
int* my_data = (int*)pool_alloc(10 * sizeof(int));
if (my_data != NULL) {
my_data[0] = 42;
printf("First element: %d\n", my_data[0]);
printf("Bytes used: %zu\n", next_free_byte);
}
return 0;
}
Why use this?
- Speed: Moving a marker (an integer addition) is much faster than the complex searching
mallocperforms. - No Fragmentation: Because the memory is one solid block, you don't end up with "holes" in your system RAM.
- Predictability: You know exactly how much memory your program uses the moment it starts.
The trade-off is simplicity: in this basic version, you can't easily "free" a middle chunk. It is best used for "scratchpad" memory where you fill the pool during a task and reset the next_free_byte to zero when the task is finished.
Key takeaway
A static memory pool provides fast, predictable allocation by slicing up a pre-allocated global array using a simple offset marker.