Created
April 12, 2016 23:42
-
-
Save joeld42/74f67cde97a789467a2f681961b89c27 to your computer and use it in GitHub Desktop.
C Allocator that tracks alloc size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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