tralloc.c (1153B)
1 #include "tralloc.h" 2 3 static size_t heapsiz = 0, heaplim = 0; 4 5 size_t tr_siz() 6 { 7 return heapsiz; 8 } 9 10 size_t tr_limit() 11 { 12 return heaplim; 13 } 14 15 size_t tr_setlimit(size_t n) 16 { 17 assert(heapsiz <= n); 18 return (heaplim = n); 19 } 20 21 size_t tr_allocsiz(void *ptr) 22 { 23 return ((size_t *)ptr)[-1]; 24 } 25 26 void *tr_malloc(size_t n) 27 { 28 size_t *ptr; 29 assert(n); 30 n += sizeof(size_t); 31 if (heaplim > 0) assert(heapsiz + n <= heaplim); 32 ptr = (size_t *)malloc(n); 33 heapsiz += n; 34 ptr[0] = n; 35 return &ptr[1]; 36 } 37 38 void *tr_calloc(size_t num, size_t n) 39 { 40 size_t *ptr, psiz; 41 assert(n && num); 42 psiz = (num * n) + sizeof(size_t); 43 if (heaplim > 0) assert(heapsiz + psiz <= heaplim); 44 ptr = (size_t *)calloc(1, psiz); 45 ptr[0] = psiz; 46 return &ptr[1]; 47 } 48 49 void *tr_realloc(void *ptr, size_t n) 50 { 51 size_t *ret, m = tr_allocsiz(ptr); 52 n += sizeof(size_t); 53 if (heaplim > 0) assert(heapsiz + (-m + n) <= heaplim); 54 ret = (size_t *)realloc((size_t *)ptr-1, n); 55 assert(ret != NULL); 56 heapsiz += (-m + n); 57 ret[0] = n; 58 return &ret[1]; 59 } 60 61 void tr_free(void *ptr) 62 { 63 size_t n = ((size_t *)ptr)[-1]; 64 if (heaplim > 0) assert(heapsiz - n >= heaplim); 65 heapsiz -= n; 66 free((size_t *)ptr-1); 67 }