bl/mem.c
author ali <ali@juiblex.co.uk>
Fri Jan 27 10:30:16 2012 +0000 (2012-01-27)
changeset 5 f600b0d1fc5d
parent 0 gclib/mem.c@c2f4c0285180
permissions -rw-r--r--
Rename to bookloupe
     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <string.h>
     4 #include <bl/mem.h>
     5 
     6 /*
     7  * A memory allocator that aborts on failure (so that the caller never
     8  * needs to handle out of memory, which we assume is very unlikely to
     9  * happen under normal circumstances on any modern machine).
    10  */
    11 void *mem_alloc(size_t nmemb,size_t size)
    12 {
    13     void *ptr=malloc(nmemb*size);
    14     if (!ptr)
    15     {
    16 	fprintf(stderr,
    17 	  "Not enough memory to allocate %lu elements of %lu bytes.\n",
    18 	  (unsigned long)nmemb,(unsigned long)size);
    19 	abort();
    20     }
    21     return ptr;
    22 }
    23 
    24 /*
    25  * As mem_new, but new memory is cleared to zero.
    26  */
    27 void *mem_alloc0(size_t nmemb,size_t size)
    28 {
    29     void *ptr=calloc(nmemb,size);
    30     if (!ptr)
    31     {
    32 	fprintf(stderr,
    33 	  "Not enough memory to allocate %lu elements of %lu bytes.\n",
    34 	  (unsigned long)nmemb,(unsigned long)size);
    35 	abort();
    36     }
    37     return ptr;
    38 }
    39 
    40 /*
    41  * Grow or shrink a memory block, aborting on failure.
    42  */
    43 void *mem_realloc(void *ptr,size_t nmemb,size_t size)
    44 {
    45     ptr=realloc(ptr,nmemb*size);
    46     if (!ptr)
    47     {
    48 	fprintf(stderr,
    49 	  "Not enough memory to allocate %lu elements of %lu bytes.\n",
    50 	  (unsigned long)nmemb,(unsigned long)size);
    51 	abort();
    52     }
    53     return ptr;
    54 }