Skip to content

Instantly share code, notes, and snippets.

@pallove
Created September 13, 2017 03:59
Show Gist options
  • Save pallove/8a42ca4cf6edd381c3dc379b46d5863b to your computer and use it in GitHub Desktop.
Save pallove/8a42ca4cf6edd381c3dc379b46d5863b to your computer and use it in GitHub Desktop.
safe malloc and free with tag
#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