Skip to content

Instantly share code, notes, and snippets.

@eduardoleon
Created March 31, 2015 16:18
Show Gist options
  • Save eduardoleon/372c3f03b9164b221402 to your computer and use it in GitHub Desktop.
Save eduardoleon/372c3f03b9164b221402 to your computer and use it in GitHub Desktop.
Simple arena allocation
#include <stdint.h>
#include <stdlib.h>
#include "arena.h"
struct block {
union {
struct block *prev;
max_align_t nope;
};
char data[];
};
void
arena_create (struct arena *arena, size_t size)
{
arena->size = size;
arena->used = size;
arena->curr = NULL;
}
void *
arena_allocate (struct arena *arena, size_t size, size_t align)
{
/* Preconditions:
* - "align" is a power of 2
* - "size" is a multiple of "align"
* - "size" is not greater than "arena->size"
*/
size_t curr = (arena->used + align - 1) & -align;
size_t next = curr + size;
/* If the current "struct block" does not have enough remaining space to
* store the requested amount of memory, allocate a new "struct block".
*/
if (next > arena->size) {
struct block *block = malloc (sizeof (struct block) + arena->size);
block->prev = arena->curr;
arena->curr = block;
curr = 0;
next = size;
}
arena->used = next;
return ((struct block *) arena->curr)->data + curr;
}
void
arena_destroy (struct arena *arena)
{
struct block *curr = arena->curr;
while (curr) {
struct block *prev = curr->prev;
free(curr);
curr = prev;
}
}
#ifndef PYON_ARENA_H
#define PYON_ARENA_H
#include <stddef.h>
struct arena {
size_t size;
size_t used;
void *curr;
};
void
arena_create (struct arena *arena, size_t size);
void *
arena_allocate (struct arena *arena, size_t size, size_t align);
void
arena_destroy (struct arena *arena);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment