Created
April 6, 2013 03:32
-
-
Save forestbelton/5324635 to your computer and use it in GitHub Desktop.
malloc wrapper that tracks size of allocated data
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
#define find_chunk(ptr) (struct mchunk*)((char*)(ptr) - offsetof(struct mchunk, data)) | |
struct mchunk { | |
size_t sz; | |
char data[]; | |
}; | |
void *qmalloc(size_t sz) { | |
struct mchunk *chunk = malloc(sizeof *chunk + sz); | |
if(chunk == NULL) | |
return NULL; | |
chunk->sz = sz; | |
return (void*)chunk->data; | |
} | |
void *qcalloc(size_t nmemb, size_t sz) { | |
void *ptr = qmalloc(nmemb * sz); | |
if(ptr == NULL) | |
return NULL; | |
return memset(ptr, '\0', nmemb * sz); | |
} | |
void *qrealloc(void *ptr, size_t sz) { | |
struct mchunk *chunk; | |
if(ptr == NULL) | |
return qmalloc(sz); | |
chunk = find_chunk(ptr); | |
chunk = realloc(chunk, sizeof *chunk + sz); | |
if(chunk == NULL) | |
return NULL; | |
chunk->sz = sz; | |
return chunk->data; | |
} | |
size_t qsize(void *ptr) { | |
struct mchunk *chunk = find_chunk(ptr); | |
return chunk->sz; | |
} | |
void qfree(void *ptr) { | |
struct mchunk *chunk; | |
if(ptr == NULL) | |
return; | |
chunk = find_chunk(ptr); | |
free(chunk); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment