tralloc

A C library that adds size information to memory allocations.
git clone git://src.gearsix.net/tralloc
Log | Files | Refs | Atom | README

commit 0a930b465cf2e90229135b2be22573a4997fc6f4
Author: gearsix <gearsix@tuta.io>
Date:   Mon,  6 Sep 2021 22:11:52 +0100

init work; did most of it this afternoon - needs testing.

Diffstat:
Astdlibw.c | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astdlibw.h | 44++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 120 insertions(+), 0 deletions(-)

diff --git a/stdlibw.c b/stdlibw.c @@ -0,0 +1,76 @@ +#include "stdlibw.h" + +static size_t _heap(char op, size_t n) +{ + static size_t siz = 0, lim = 0; + switch (op) { + case 0: break; + case '!': return (lim = n); + case '?': return lim; + case '+': + if (lim > 0) assert(siz + n <= lim); + siz += n; + break; + case '-': + if (lim > 0) assert(siz - n >= lim); + siz -= n; + break; + default: /* invalid op */ + assert(1); + } + return siz; +} + +size_t heapsiz() +{ + return _heap(0, 0); +} + +size_t heaplim() +{ + return _heap('?', 0); +} + +size_t limheap(size_t n) +{ + return _heap('!', 0); +} + +size_t sizeofw(void *ptr) +{ + return ((size_t *)ptr)[-1]; +} + +void *mallocw(size_t siz) +{ + size_t *ptr; + assert(siz); + ptr = (size_t *)malloc(siz += sizeof(size_t)); + _heap('+', siz); + ptr[0] = siz; + return &ptr[1]; +} + +void *callocw(size_t num, size_t siz) +{ + size_t *ptr; + assert(siz && (size_t)-1/num); + ptr = (size_t *)mallocw(num * siz); + return ptr; +} + +void *realloc(void *ptr, size_t siz) +{ + size_t *ret, psiz = sizeofw(ptr); + assert(siz > psiz); + ret = mallocw(siz); + while (--psiz > 0) ret[psiz] = ((size_t *)ptr)[psiz]; + freew(ptr); + return ret; +} + +void freew(void *ptr) +{ + _heap('-', ((size_t *)ptr)[-1]); + free((size_t *)ptr-1); +} diff --git a/stdlibw.h b/stdlibw.h @@ -0,0 +1,44 @@ +#ifndef STDLIBW +#define STDLIBW + +#include <stdlib.h> +#include <assert.h> + +/** heapsiz - heap size? + * returns the currently tracked `heapsiz` +**/ +size_t heapsiz(); + +/** heaplim - heapsiz limit? + * returns the current limit set on `heapsiz`. + * if 0 is returned, there is no limit. +**/ +size_t heaplim(); + +/** limheap - limit heapsiz + * set the limit on `heapsiz` to `siz`, returns the set limit. + * if the returned value is not `n`, then the call failed. +**/ +size_t limheap(size_t n); + +/** + * sizeofw - sizeof wrapper + * returns the number of allocated bytes for `ptr`. + * will fail if called on a pointer not allocated by stdlibw. +**/ +size_t sizeofw(void *ptr); + +/** mallocw - malloc wrapper + * malloc (sizeof(size_t) + siz) bytes and return that pointer from [1] + * [0] is used to store `siz`. + * `(siz + sizeof(size_t))` will be added to `heapsiz` +**/ +void *mallocw(size_t siz); + +void *callocw(size_t num, size_t siz); + +void *reallocw(void *ptr, size_t siz); + +void freew(void *ptr); + +#endif