Created
September 13, 2017 03:59
-
-
Save pallove/8a42ca4cf6edd381c3dc379b46d5863b to your computer and use it in GitHub Desktop.
safe malloc and free with tag
This file contains 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 <stdlib.h> | |
#include <string.h> | |
#define MAGIC_TAG 0x11223344 | |
inline static void* my_malloc(int size) { | |
void* ptr = malloc(size + sizeof(MAGIC_TAG)); | |
int *p = (int *) ptr; | |
*p = MAGIC_TAG; | |
return p + 1; | |
} | |
inline static void my_free(void *ptr) { | |
if (ptr == NULL) return; | |
int *p = (int *) ptr - 1; | |
if (*p == MAGIC_TAG) { | |
*p = 0; | |
free(p); | |
} | |
} | |
int main() { | |
char *ptr = my_malloc(100); | |
my_free(ptr); | |
my_free(ptr); | |
my_free(ptr); | |
ptr = NULL; | |
my_free(ptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment