Why assign NULL on a pointer after a free?

9

I see in many codes assigning NULL to a pointer just after a free , type:

free(p);
p = NULL;

What would be the advantage of this?

    
asked by anonymous 05.06.2018 / 15:10

2 answers

8

This is a good practice that helps you avoid unexpected behaviors and greatly facilitates treatment of errors.

After calling free(p) the p pointer will no longer point to a valid memory address, which makes it a Ponteiro Selvagem .

Manipulating Ponteiros Selvagens almost always causes the Comportamento Indefinido program.

It turns out that in C , it is not possible to determine if a pointer is a Ponteiro Selvagem .

"Forcing" the pointer that just suffered free() to NULL ensures that there will be Ponteiros Selvagens within its scope, which will certainly facilitate debugging and error handling in your program. >

Note that initializing pointers with NULL is also part of the same idea, as this can happen with a Ponteiro não Inicializado

Good practice would be something like:

void foobar( void )
{
    char * p = NULL;

    /* ... */

    free(p);
    p = NULL;

    /* ... */

    if( p == NULL )
    {
        /* ... */
    }
}
    
05.06.2018 / 16:44
6

This heavily depends on the context in which it is used. In particular the pointer after free is not usable. With NULL value, it is usable. For example:

while (p != NULL) {
    // Um monte de código usando p aqui.

    if (alguma coisa) {
        free(p);
        p = NULL;
    }
}

Finally, if the pointer variable can be somehow referenced after free , it makes sense that NULL is assigned to it to avoid referring to something that no longer exists. The NULL value can be tested, whereas an invalid pointer can not.

    
05.06.2018 / 15:52