The standard way to free dynamically allocated memory in C is through the function:
void free(void *ptr); |
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:
void safe_free(void **ptr) | |
{ | |
free(*ptr); | |
*ptr = NULL; | |
} |
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:
#define safe_free(x)\ | |
free((void*)x);\ | |
x = NULL |
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.
int main() | |
{ | |
int ptr = malloc(10); | |
// some code | |
safe_free(ptr); | |
return 0; | |
} |
Done.
No comments:
Post a Comment