Setting a pointer to NULL
after free
is a dubious practice that is often popularized as a "good programming" rule on a patently false premise. It is one of those fake truths that belong to the "sounds right" category but in reality achieve absolutely nothing useful (and sometimes leads to negative consequences).
Allegedly, setting a pointer to NULL
after free
is supposed to prevent the dreaded "double free" problem when the same pointer value is passed to free
more than once. In reality though, in 9 cases out of 10 the real "double free" problem occurs when different pointer objects holding the same pointer value are used as arguments for free
. Needless to say, setting a pointer to NULL
after free
achieves absolutely nothing to prevent the problem in such cases.
Of course, it is possible to run into "double free" problem when using the same pointer object as an argument to free
. However, in reality situations like that normally indicate a problem with the general logical structure of the code, not a mere accidental "double free". A proper way to deal with the problem in such cases is to review and rethink the structure of the code in order to avoid the satiation when the same pointer is passed to free
more than once. In such cases setting the pointer to NULL
and considering the problem "fixed" is nothing more than an attempt to sweep the problem under the carpet. It simply won't work in general case, because the problem with the code structure will always find another way to manifest itself.
Finally, if your code is specifically designed to rely on the pointer value being NULL
or not NULL
, it is perfectly fine to set the pointer value to NULL
after free
. But as a general "good practice" rule (as in "always set your pointer to NULL
after free
") it is, once again, a well-known and pretty useless fake, often followed by some for purely religious, voodoo-like reasons.