Skip to content

Instantly share code, notes, and snippets.

@C0deH4cker
Created November 14, 2015 05:36
Show Gist options
  • Save C0deH4cker/60029170163d41a6361c to your computer and use it in GitHub Desktop.
Save C0deH4cker/60029170163d41a6361c to your computer and use it in GitHub Desktop.
Safer way to free a variable in C
#include <stdlib.h>
/*! Frees the pointer pointed to by the parameter and then sets it to NULL */
#define destroy(pptr) do { \
__typeof__(*(pptr)) volatile* _pptr = (pptr); \
if(!_pptr) { \
break; \
} \
free(*_pptr); \
*_pptr = NULL; \
} while(0)
/*
This is a safer alternative to calling free() directly, and is no more difficult to use.
Instead of calling free(myVar), just call destroy(&myVar). This will call free() on myVar
and then set myVar to NULL in a type safe and optimization safe manner. As with free(),
destroy(NULL) is safe and is a no-op. Works on any compiler that supports __typeof__, which
include gcc and clang but not MSVC unfortunately. If you're using MSVC (Visual Studio), instead
do the following (which I believe is fully type safe due to the ErrorIfNotAtLeastDoublePointer()
macro, but I'm not 100% sure of that).
*/
/*! Frees the pointer pointed to by the parameter and then sets it to NULL */
#define ErrorIfNotAtLeastDoublePointer(pptr) sizeof(&**(pptr))
#define destroy(pptr) (ErrorIfNotAtLeastDoublePointer(pptr), _destroy((volatile void**)(pptr)))
static inline void _destroy(volatile void** pptr) {
if(!pptr) {
return;
}
free((void*)*pptr);
*pptr = NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment