dcbde236 |
1 | /* |
2 | * PuTTY memory-handling header. |
3 | */ |
4 | |
5 | #ifndef PUTTY_PUTTYMEM_H |
6 | #define PUTTY_PUTTYMEM_H |
7 | |
32874aea |
8 | #include <stddef.h> /* for size_t */ |
9 | #include <string.h> /* for memcpy() */ |
db9c0f86 |
10 | |
11 | |
dcbde236 |
12 | /* #define MALLOC_LOG do this if you suspect putty of leaking memory */ |
13 | #ifdef MALLOC_LOG |
46cfeac8 |
14 | #define smalloc(z) (mlog(__FILE__,__LINE__), safemalloc(z,1)) |
15 | #define snmalloc(z,s) (mlog(__FILE__,__LINE__), safemalloc(z,s)) |
16 | #define srealloc(y,z) (mlog(__FILE__,__LINE__), saferealloc(y,z,1)) |
9af6afe3 |
17 | #define snrealloc(y,z,s) (mlog(__FILE__,__LINE__), saferealloc(y,z,s)) |
dcbde236 |
18 | #define sfree(z) (mlog(__FILE__,__LINE__), safefree(z)) |
19 | void mlog(char *, int); |
20 | #else |
46cfeac8 |
21 | #define smalloc(z) safemalloc(z,1) |
22 | #define snmalloc safemalloc |
23 | #define srealloc(y,z) saferealloc(y,z,1) |
24 | #define snrealloc saferealloc |
dcbde236 |
25 | #define sfree safefree |
26 | #endif |
27 | |
46cfeac8 |
28 | void *safemalloc(size_t, size_t); |
29 | void *saferealloc(void *, size_t, size_t); |
dcbde236 |
30 | void safefree(void *); |
31 | |
3d88e64d |
32 | /* |
33 | * Direct use of smalloc within the code should be avoided where |
34 | * possible, in favour of these type-casting macros which ensure |
35 | * you don't mistakenly allocate enough space for one sort of |
36 | * structure and assign it to a different sort of pointer. |
f0f0ae7f |
37 | * |
38 | * The nasty trick in sresize with sizeof arranges for the compiler, |
39 | * in passing, to type-check the expression ((type *)0 == (ptr)), i.e. |
40 | * to type-check that the input pointer is a pointer to the correct |
41 | * type. The construction sizeof(stuff) ? (b) : (b) looks like a |
42 | * violation of the first principle of safe macros, but in fact it's |
43 | * OK - although it _expands_ the macro parameter more than once, it |
44 | * only _evaluates_ it once, so it's still side-effect safe. |
3d88e64d |
45 | */ |
46cfeac8 |
46 | #define snew(type) ((type *)snmalloc(1, sizeof(type))) |
47 | #define snewn(n, type) ((type *)snmalloc((n), sizeof(type))) |
f0f0ae7f |
48 | #define sresize(ptr, n, type) \ |
49 | ((type *)snrealloc(sizeof((type *)0 == (ptr)) ? (ptr) : (ptr), \ |
50 | (n), sizeof(type))) |
db9c0f86 |
51 | |
dcbde236 |
52 | #endif |