| 1 | /* |
| 2 | * malloc.c: safe wrappers around malloc, realloc, free, strdup |
| 3 | */ |
| 4 | |
| 5 | #include <stdlib.h> |
| 6 | #include <string.h> |
| 7 | #include "puzzles.h" |
| 8 | |
| 9 | /* |
| 10 | * smalloc should guarantee to return a useful pointer - Halibut |
| 11 | * can do nothing except die when it's out of memory anyway. |
| 12 | */ |
| 13 | void *smalloc(size_t size) { |
| 14 | void *p; |
| 15 | p = malloc(size); |
| 16 | if (!p) |
| 17 | fatal("out of memory"); |
| 18 | return p; |
| 19 | } |
| 20 | |
| 21 | /* |
| 22 | * sfree should guaranteeably deal gracefully with freeing NULL |
| 23 | */ |
| 24 | void sfree(void *p) { |
| 25 | if (p) { |
| 26 | free(p); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | /* |
| 31 | * srealloc should guaranteeably be able to realloc NULL |
| 32 | */ |
| 33 | void *srealloc(void *p, size_t size) { |
| 34 | void *q; |
| 35 | if (p) { |
| 36 | q = realloc(p, size); |
| 37 | } else { |
| 38 | q = malloc(size); |
| 39 | } |
| 40 | if (!q) |
| 41 | fatal("out of memory"); |
| 42 | return q; |
| 43 | } |
| 44 | |
| 45 | /* |
| 46 | * dupstr is like strdup, but with the never-return-NULL property |
| 47 | * of smalloc (and also reliably defined in all environments :-) |
| 48 | */ |
| 49 | char *dupstr(const char *s) { |
| 50 | char *r = smalloc(1+strlen(s)); |
| 51 | strcpy(r,s); |
| 52 | return r; |
| 53 | } |