|
21 | 21 | #include <stddef.h> |
22 | 22 | #include <stdlib.h> |
23 | 23 |
|
24 | | -extern size_t g_allocated_bytes; |
| 24 | +/* Platform shim for "how many usable bytes are at this malloc'd pointer". |
| 25 | + Apple's malloc_size, glibc's malloc_usable_size, MSVC's _msize. The |
| 26 | + returned size is the *usable* size (may exceed the requested size by a |
| 27 | + few bytes of allocator rounding), but alloc and free use the same |
| 28 | + function so the running totals stay symmetric. */ |
| 29 | +#if defined(__APPLE__) |
| 30 | +#include <malloc/malloc.h> |
| 31 | +#define TRACKED_BLOCK_SIZE(p) malloc_size(p) |
| 32 | +#elif defined(_WIN32) || defined(_WIN64) |
| 33 | +#include <malloc.h> |
| 34 | +#define TRACKED_BLOCK_SIZE(p) _msize(p) |
| 35 | +#else |
| 36 | +#include <malloc.h> |
| 37 | +#define TRACKED_BLOCK_SIZE(p) malloc_usable_size(p) |
| 38 | +#endif |
| 39 | + |
| 40 | +extern size_t g_allocated_bytes; /* current live bytes */ |
| 41 | +extern size_t g_peak_bytes; /* high-water mark since last reset */ |
25 | 42 |
|
26 | 43 | static inline void *SP_MALLOC(size_t size) |
27 | 44 | { |
28 | 45 | void *ptr = malloc(size); |
29 | | - if (ptr) g_allocated_bytes += size; |
| 46 | + if (ptr) |
| 47 | + { |
| 48 | + g_allocated_bytes += TRACKED_BLOCK_SIZE(ptr); |
| 49 | + if (g_allocated_bytes > g_peak_bytes) g_peak_bytes = g_allocated_bytes; |
| 50 | + } |
30 | 51 | return ptr; |
31 | 52 | } |
32 | 53 |
|
33 | 54 | static inline void *SP_CALLOC(size_t count, size_t size) |
34 | 55 | { |
35 | 56 | void *ptr = calloc(count, size); |
36 | | - if (ptr) g_allocated_bytes += count * size; |
| 57 | + if (ptr) |
| 58 | + { |
| 59 | + g_allocated_bytes += TRACKED_BLOCK_SIZE(ptr); |
| 60 | + if (g_allocated_bytes > g_peak_bytes) g_peak_bytes = g_allocated_bytes; |
| 61 | + } |
37 | 62 | return ptr; |
38 | 63 | } |
39 | 64 |
|
| 65 | +static inline void SP_FREE(void *ptr) |
| 66 | +{ |
| 67 | + if (ptr) |
| 68 | + { |
| 69 | + g_allocated_bytes -= TRACKED_BLOCK_SIZE(ptr); |
| 70 | + free(ptr); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/* Auto-route plain malloc/calloc/free in caller translation units through |
| 75 | + the tracked wrappers. Defined AFTER the wrapper bodies so SP_MALLOC / |
| 76 | + SP_CALLOC / SP_FREE themselves still see the real stdlib symbols. */ |
| 77 | +#define malloc SP_MALLOC |
| 78 | +#define calloc SP_CALLOC |
| 79 | +#define free SP_FREE |
| 80 | + |
40 | 81 | #endif /* TRACKED_ALLOC_H */ |
0 commit comments