Build an arena: one big block, small aligned allocations handed out from it, and everything freed with a single call.
Solution
main.c
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
enum { ALIGN = 16 };
struct arena {
unsigned char *base;
size_t used, size;
};
bool arena_init(struct arena *a, size_t size) {
a->base = malloc(size);
a->used = 0;
a->size = size;
return a->base != NULL;
}
void *arena_alloc(struct arena *a, size_t n) {
size_t start = (a->used + ALIGN - 1) / ALIGN * ALIGN; /* round up to 16 */
if (start > a->size || n > a->size - start)
return NULL; /* not enough room */
a->used = start + n;
return a->base + start;
}
void arena_free_all(struct arena *a) {
free(a->base); /* one free for everything */
a->base = NULL;
}
int main(void) {
struct arena a;
if (!arena_init(&a, 64))
return 1;
int *x = arena_alloc(&a, 3 * sizeof *x);
char *name = arena_alloc(&a, 10);
double *big = arena_alloc(&a, 64);
printf("x at offset %td, name at offset %td\n",
(unsigned char *) x - a.base, (unsigned char *) name - a.base);
printf("64 more bytes: %s\n", big != NULL ? "ok" : "out of space");
printf("used %zu of %zu\n", a.used, a.size);
arena_free_all(&a);
return 0;
}
Output Verified by compiling and running
x at offset 0, name at offset 16
64 more bytes: out of space
used 26 of 64
Allocation is just "round up and add" – far faster than malloc() – and every object is freed at once. Games, compilers and web servers use arenas for per-frame or per-request data. The size check is written as n > size - start so it cannot overflow.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!