Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
C Allocator that tracks alloc size
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
typedef struct
size_t alloc_size;
} block_header;
void *my_alloc( size_t sz )
block_header *hdr = (block_header*)malloc(sizeof(block_header) + sz );
hdr->alloc_size = sz;
printf("hdr is %p (%p)\n", hdr, hdr+1);
return hdr+1;
size_t my_buffsize( void *ptr )
block_header *hdr = (block_header*)ptr;
return (hdr-1)->alloc_size;
void my_free( void *ptr )
block_header *hdr = (block_header*)ptr;
int main()
void *ptr = my_alloc( 8762 );
printf("buffer size of ptr is %ld\n", my_buffsize(ptr) );
my_free( ptr );
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.