1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
/* xmalloc.c - Do-or-die Memory management functions.
*
* Created by Kevin Locke (from numerous canonical examples)
*
* I hereby place this file in the public domain. It may be freely reproduced,
* distributed, used, modified, built upon, or otherwise employed by anyone
* for any purpose without restriction.
*/
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
#endif
void *xmalloc(size_t size)
{
void *allocated = malloc(size);
if (allocated == NULL) {
fprintf(stderr, "Error: Insufficient memory "
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
"(attempt to malloc %zu bytes)\n", size);
#else
"(attempt to malloc %u bytes)\n", (unsigned int) size);
#endif
exit(EXIT_FAILURE);
}
return allocated;
}
void *xcalloc(size_t num, size_t size)
{
void *allocated = calloc(num, size);
if (allocated == NULL) {
fprintf(stderr, "Error: Insufficient memory "
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
"(attempt to calloc %zu bytes)\n", size);
#else
"(attempt to calloc %u bytes)\n", (unsigned int) size);
#endif
exit(EXIT_FAILURE);
}
return allocated;
}
void *xrealloc(void *ptr, size_t size)
{
void *allocated;
/* Protect against non-standard behavior */
if (ptr == NULL) {
allocated = malloc(size);
} else {
allocated = realloc(ptr, size);
}
if (allocated == NULL) {
fprintf(stderr, "Error: Insufficient memory "
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
"(attempt to realloc %zu bytes)\n", size);
#else
"(attempt to realloc %u bytes)\n", (unsigned int) size);
#endif
exit(EXIT_FAILURE);
}
return allocated;
}
|