Skip to content

Instantly share code, notes, and snippets.

@arc
Created October 23, 2014 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arc/6a7c144f03b744e14dbc to your computer and use it in GitHub Desktop.
Save arc/6a7c144f03b744e14dbc to your computer and use it in GitHub Desktop.
/* Trivial (and totally untested) slab allocator */
struct slab;
struct slab {
struct slab *prev;
void *buf;
size_t avail, orig_size;
};
struct slab *slab_create(size_t initial_size) {
/* XXX: check for overflow in addition */
struct slab *slab = malloc(initial_size + sizeof(struct slab));
slab->prev = 0;
slab->buf = slab + 1;
slab->avail = initial_size;
slab->orig_size = initial_size;
}
void *slab_alloc(struct slab *slab, size_t bytes) {
if (bytes > slab->avail) {
size_t new_size = slab->orig_size;
if (bytes > new_size) {
new_size = bytes;
}
/* XXX: check for overflow in addition */
struct slab *new_slab = malloc(new_size + sizeof(struct slab));
new_slab->prev = slab;
new_slab->buf = new_slab + 1;
new_slab->avail = new_size;
new_slab->orig_size = new_size;
slab = new_slab;
}
{
void *p = slab->buf;
/* XXX: round up bytes for alignment of next allocation (but
* ensuring that slab->avail won't go negative) */
slab->buf += bytes;
slab->avail -= bytes;
return p;
}
}
void slab_destroy(struct slab *slab) {
if (slab->prev) {
slab_destroy(slab->prev);
}
free(slab);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment