X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=src%2Falloc.c;h=a7b20283f38588f7fd7f955f692c0d624e4eff29;hb=8fa7f3f6640c0eec450149cf5ccfab15d5391f55;hp=8d1e39a633e78a967a1315b6c799e72afd33bd22;hpb=560701a881f119bcff6f0bd284c9f01c30c64ad3;p=pspp diff --git a/src/alloc.c b/src/alloc.c index 8d1e39a633..a7b20283f3 100644 --- a/src/alloc.c +++ b/src/alloc.c @@ -19,109 +19,14 @@ #include #include "alloc.h" -#include #include -#include "error.h" -#include "str.h" - -/* Public functions. */ -/* Allocates a block of SIZE bytes and returns it. - If SIZE is 0, returns a null pointer. - Aborts if unsuccessful. */ +/* Allocates and returns N elements of S bytes each. + N must be nonnegative, S must be positive. + Returns a null pointer if the memory cannot be obtained, + including the case where N * S overflows the range of size_t. */ void * -xmalloc (size_t size) +nmalloc (size_t n, size_t s) { - void *vp; - if (size == 0) - return NULL; - - vp = malloc (size); - if (!vp) - out_of_memory (); - - return vp; -} - - -/* Allocates a continous block of N_MEMB by SIZE elements, with all - bits set to 0. - Aborts if unsuccessful. -*/ -void * -xcalloc (size_t n_memb, size_t size) -{ - const size_t prod = size * n_memb; - void *vp = 0; - - if (prod == 0) - return NULL; - - /* Trap overflow errors */ - assert ( prod >= size ); - assert ( prod >= n_memb ) ; - - vp = xmalloc ( prod ); - memset (vp, 0, prod); - return vp; -} - - - -/* If SIZE is 0, then block PTR is freed and a null pointer is - returned. - Otherwise, if PTR is a null pointer, then a new block is allocated - and returned. - Otherwise, block PTR is reallocated to be SIZE bytes in size and - the new location of the block is returned. - Aborts if unsuccessful. */ -void * -xrealloc (void *ptr, size_t size) -{ - void *vp; - if (!size) - { - if (ptr) - free (ptr); - - return NULL; - } - - if (ptr) - vp = realloc (ptr, size); - else - vp = malloc (size); - - if (!vp) - out_of_memory (); - - return vp; -} - -/* Makes a copy of string S in malloc()'d memory and returns the copy. - S must not be a null pointer. */ -char * -xstrdup (const char *s) -{ - size_t size; - char *t; - - assert (s != NULL); - - size = strlen (s) + 1; - - t = malloc (size); - if (!t) - out_of_memory (); - - memcpy (t, s, size); - return t; -} - -/* Report an out-of-memory condition and abort execution. */ -void -out_of_memory (void) -{ - fprintf (stderr, "virtual memory exhausted\n"); - exit (EXIT_FAILURE); + return !xalloc_oversized (n, s) ? malloc (n * s) : NULL; }