i’m making a memory allocation/deallocation function
it’s simple
inline void safedealloc ( void *mem )
{
if ( mem ) { free( mem ); mem = NULL; }
}
it’s working fine .. however after using it few times with a program
i noticed that when calling it in something like
safedealloc( (char *)name );
safedealloc( (char *)name );
causes error .. name supposed to be null after first call . but it doesn’t and the second call with invalid pointer ofc causes error .. why isn’t null being assigned to name as it should ?
PS: name is properly allocated using malloc and with valid size and contents
It almost certainly is not working fine, it is pointless, and in C++ the way you allocate memory is with new and delete, not malloc and free. There is no need to check for a NULL pointer – free (NULL ) is well defined in both C and C++. And your assignment of NULL to the function parameter does nothing – it only modifies the parameter, not its value back in the calling program.
And lastly, if you find yourself writing code like this:
the thing to do is to fix the code so you don’t free the pointer twice, not to obfuscate things by sticking a band-aid on bad code.