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