720a8fb7 |
1 | /* |
2 | * malloc.c: safe wrappers around malloc, realloc, free, strdup |
3 | */ |
4 | |
5 | #include <stdlib.h> |
2ef96bd6 |
6 | #include <string.h> |
720a8fb7 |
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(int 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, int 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 | */ |
ab30d7be |
49 | char *dupstr(const char *s) { |
720a8fb7 |
50 | char *r = smalloc(1+strlen(s)); |
51 | strcpy(r,s); |
52 | return r; |
53 | } |