Thursday, October 15, 2020

Freeing memory safely in C

 The standard way to free dynamically allocated memory in C is through the function: 

However, after the function frees the dynamically allocated memory the pointer still points to the same -now invalid- location, making it a dangling pointer.

a common solution to this problem is to make sure that you assign NULL to every pointer after you free it. However, it would be nice if you could call only one function that does the 2 steps for you; freeing the memory and assigning NULL to the pointer.

You could do this by making a wrapper function around free, but this would require a pointer to a pointer: 

However, I do not like pointers to pointers very much and tend to avoid using them whenever I can. I'd much rather use a macro:

Notice the absence of a semicolon at the final statement, that's because I will add that semicolon myself each time I invoke the macro to stay compliant with C's syntax.


Done.