That is the typical method but depends on what you're doing. It is not required and I see your point, but if you're going to be using pointer allocations this way you might want to make a wrapper for free() that sets it for you:
Code:void * safe_free(void * ptr) { if(ptr) free(ptr); return NULL; } var = safe_free(var);
It is safe to free a null pointer, so one could write:
But then since this requires one to remember to assign the return value of safe_free() back to the pointer, I see no benefit over just writing:Code:void * safe_free(void * ptr) { free(ptr); return NULL; }
Code:free(var); var = NULL;
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Last edited by rasta_freak; 08-04-2008 at 10:09 AM.
I would prefer something like this:
--Code:void safe_free(void **ptr) { if (ptr) // Check for stupid programmer errors { free(*ptr); *ptr = NULL; } } // And to complete it... #define free(x) safe_free(&x)
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Yes all very good points of preference... and back to what was being said:
"... so do something... or not"
or better yet, you could just:Rather than having an IF, in that case.Code:assert(ptr);
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"