Home > OS >  C - free() wrapper for deallocation's best practices
C - free() wrapper for deallocation's best practices

Time:10-23

The best practice for free() is to assign a NULL after freeing a "dynamically allocated" pointer.
But having 50 instances of:
free(p); p = NULL;
Isn't the most compelling. So I thought about creating a function that does it and calling it SmartFree(), but for some reason It creates issues for me.
Any body has an example for such function?
FYI - I saw this post `free()` wrapper
But I would like to use that function to free many data types. So I used void *, but Im concerned that's part of the issue.

CodePudding user response:

Richard M Reese wrote a great book called - Understanding and using C pointers.
The book name is really on point. It has many scenarios for questions similar to yours.
Check pages 70-71 of that book.
It has a cool function for your question a cool macro to easily call that function without casting the parameter we are passing.
http://www.sauleh.ir/fc98/static_files/materials/Richard Reese-Understanding and Using C Pointers-O'Reilly Media (2013).pdf

  • Related