Setting variable to NULL after free


In my company there is a coding rule that says, after freeing any memory, reset the variable to NULL. For example …

void some_func () 
    int *nPtr;

    nPtr = malloc (100);

    free (nPtr);
    nPtr = NULL;


I feel that, in cases like the code shown above, setting to NULL does not have any meaning. Or am I missing something?

If there is no meaning in such cases, I am going to take it up with the "quality team" to remove this coding rule. Please advice.

Best Solution

Setting unused pointers to NULL is a defensive style, protecting against dangling pointer bugs. If a dangling pointer is accessed after it is freed, you may read or overwrite random memory. If a null pointer is accessed, you get an immediate crash on most systems, telling you right away what the error is.

For local variables, it may be a little bit pointless if it is "obvious" that the pointer isn't accessed anymore after being freed, so this style is more appropriate for member data and global variables. Even for local variables, it may be a good approach if the function continues after the memory is released.

To complete the style, you should also initialize pointers to NULL before they get assigned a true pointer value.