1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/gclib/mem.c Tue Jan 24 23:54:05 2012 +0000
1.3 @@ -0,0 +1,54 @@
1.4 +#include <stdlib.h>
1.5 +#include <stdio.h>
1.6 +#include <string.h>
1.7 +#include <gclib/mem.h>
1.8 +
1.9 +/*
1.10 + * A memory allocator that aborts on failure (so that the caller never
1.11 + * needs to handle out of memory, which we assume is very unlikely to
1.12 + * happen under normal circumstances on any modern machine).
1.13 + */
1.14 +void *mem_alloc(size_t nmemb,size_t size)
1.15 +{
1.16 + void *ptr=malloc(nmemb*size);
1.17 + if (!ptr)
1.18 + {
1.19 + fprintf(stderr,
1.20 + "Not enough memory to allocate %lu elements of %lu bytes.\n",
1.21 + (unsigned long)nmemb,(unsigned long)size);
1.22 + abort();
1.23 + }
1.24 + return ptr;
1.25 +}
1.26 +
1.27 +/*
1.28 + * As mem_new, but new memory is cleared to zero.
1.29 + */
1.30 +void *mem_alloc0(size_t nmemb,size_t size)
1.31 +{
1.32 + void *ptr=calloc(nmemb,size);
1.33 + if (!ptr)
1.34 + {
1.35 + fprintf(stderr,
1.36 + "Not enough memory to allocate %lu elements of %lu bytes.\n",
1.37 + (unsigned long)nmemb,(unsigned long)size);
1.38 + abort();
1.39 + }
1.40 + return ptr;
1.41 +}
1.42 +
1.43 +/*
1.44 + * Grow or shrink a memory block, aborting on failure.
1.45 + */
1.46 +void *mem_realloc(void *ptr,size_t nmemb,size_t size)
1.47 +{
1.48 + ptr=realloc(ptr,nmemb*size);
1.49 + if (!ptr)
1.50 + {
1.51 + fprintf(stderr,
1.52 + "Not enough memory to allocate %lu elements of %lu bytes.\n",
1.53 + (unsigned long)nmemb,(unsigned long)size);
1.54 + abort();
1.55 + }
1.56 + return ptr;
1.57 +}