main shrub/shrubtools / shared / alloc.c
 1/* Public domain. */
 2
 3#include <errno.h>
 4#include <stdlib.h>
 5#include "alloc.h"
 6#include "error.h"
 7
 8#define ALIGNMENT 16 /* XXX: assuming that this alignment is enough */
 9#define SPACE 2048 /* must be multiple of ALIGNMENT */
10
11typedef union { char irrelevant[ALIGNMENT]; double d; } aligned;
12static aligned realspace[SPACE / ALIGNMENT];
13#define space ((char *) realspace)
14static unsigned int avail = SPACE; /* multiple of ALIGNMENT; 0<=avail<=SPACE */
15
16/*@null@*//*@out@*/char *alloc(n)
17unsigned int n;
18{
19  char *x;
20  n = ALIGNMENT + n - (n & (ALIGNMENT - 1)); /* XXX: could overflow */
21  if (n <= avail) { avail -= n; return space + avail; }
22  x = malloc(n);
23  if (!x) errno = error_nomem;
24  return x;
25}
26
27void alloc_free(x)
28char *x;
29{
30  if (x >= space)
31    if (x < space + SPACE)
32      return; /* XXX: assuming that pointers are flat */
33  free(x);
34}