Skip to content

Instantly share code, notes, and snippets.

@joeld42
Created April 12, 2016 23:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeld42/74f67cde97a789467a2f681961b89c27 to your computer and use it in GitHub Desktop.
Save joeld42/74f67cde97a789467a2f681961b89c27 to your computer and use it in GitHub Desktop.
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;
free(hdr-1);
}
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