tralloc

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

original-draft.c (raw) (1357B)


   1 /* htrack.c
   2  * example of how to track heap-heapsiz during runtime
   3  * -gearsix
   4  */
   5 #include <stdio.h>
   6 #include <stdlib.h>
   7 #include <string.h>
   8 
   9 static size_t heapsiz = 0;
  10 
  11 // mallocw (malloc wrapper) allocates nbytes + sizeof(size_t).
  12 // the allocated number of bytes for the pointer is stored in [0],
  13 // the memory block requested by the user is stored from [1]..[n].
  14 // note that ptr[1] is returned.
  15 void *mallocw(size_t nbytes)
  16 {
  17 	nbytes += sizeof(size_t);
  18 	heapsiz += nbytes;
  19 	size_t *ptr = malloc(nbytes);
  20 	ptr[0] = nbytes;
  21 	return &ptr[1];
  22 }
  23 
  24 // sizeofw (sizeof wrapper) check [-1] for the size_t value set by
  25 // mallocw. ptr must have been allocated by mallocw to avoid issues.
  26 size_t sizeofw(void *ptr)
  27 {
  28 	return ((size_t *)ptr)[-1];
  29 }
  30 
  31 // freew (free wrapper) frees *ptr from [-1], will probably cause
  32 // an issue if the ptr wasn't allocated by mallocw.
  33 void freew(void *ptr)
  34 {
  35 	heapsiz -= sizeofw(ptr);
  36 	free((size_t *)ptr-1);
  37 }
  38 
  39 int main(int argc, char *argv[])
  40 {
  41 	printf("heapsiz: %lu\n", heapsiz);
  42 
  43 	char *str = mallocw(6);
  44 	if (str == NULL) {
  45 		fprintf(stderr, "mallocw failed");
  46 		return EXIT_FAILURE;
  47 	}
  48 	strcpy(str, "foobar");
  49 	printf("str = '%s', strlen %d, sizeof %d\n", str, strlen(str), sizeofw(str));
  50 	printf("heapsiz: %lu\n", heapsiz);
  51 	puts("freeing str...");
  52 	freew(str);
  53 	printf("heapsiz: %lu\n", heapsiz);
  54 
  55 	return EXIT_SUCCESS;
  56 }