Example: Nested memory scopes using arena stack frames.
Example: Nested memory scopes using arena stack frames.This example demonstrates how to manage temporary memory in nested scopes using t_arena_stack. Each "code block" pushes a new frame and allocates temporary memory for simulated tokens. When the block ends, the memory is discarded by popping the frame.
#include <stdio.h>
#include <string.h>
void parse_block(
t_arena_stack* stack,
const char* label,
int depth)
{
printf("-> Entering block: %s\n", label);
if (token1 && token2)
{
snprintf(token1, 64, "[%s] token1", label);
snprintf(token2, 64, "[%s] token2", label);
printf(" Allocated: %s | %s\n", token1, token2);
}
if (depth < 2)
{
char child_label[32];
snprintf(child_label, sizeof(child_label), "%s.child", label);
parse_block(stack, child_label, depth + 1);
}
printf("<- Exiting block: %s\n", label);
}
int main(void)
{
if (!arena)
{
fprintf(stderr, "Failed to create arena.\n");
return 1;
}
parse_block(&stack, "root", 0);
return 0;
}
void * arena_alloc(t_arena *arena, size_t size)
void arena_delete(t_arena **arena)
t_arena * arena_create(size_t size, bool allow_grow)
Stack-based scope management for memory arenas.
t_arena * arena
Arena associated with this stack.
void arena_stack_push(t_arena_stack *stack)
Push the current arena state onto the stack.
void arena_stack_pop(t_arena_stack *stack)
Pop and restore the last saved state from the stack.
void arena_stack_init(t_arena_stack *stack, t_arena *arena)
Initialize an arena stack with a given arena.
void arena_stack_clear(t_arena_stack *stack)
Clear all stack frames without modifying arena state.
Stack structure for scoped arena memory control.
The main memory arena structure used for fast allocation.