Why assign NULL on a pointer after a free?

Asked

Viewed 562 times

9

I see in many codes assign NULL on a pointer just after a free, guy:

free(p);
p = NULL;

What good would that do?

2 answers

10


It is a good practice that helps avoid unexpected behavior and greatly facilitates the handling of errors.

After the call from free(p) the pointer p no longer points to a valid memory address, which makes it a Ponteiro Selvagem.

Manipulate Ponteiros Selvagens almost always cause the Comportamento Indefinido of the program.

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

"Force" the pointer you just suffered free() for NULL guarantees that there will be no Ponteiros Selvagens within its scope, which will certainly facilitate debugging and bug tracking in your program.

Note that initialize pointers with NULL is also part of the same idea, because the same 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 )
    {
        /* ... */
    }
}

8

This depends a lot on the context where it is used. Especially the pointer after the free is not usable. With the value NULL, it is usable. For example:

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

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

Anyway, if the pointer variable can be somehow referenced after the free, it makes sense that NULL is assigned to it to avoid reference to something that no longer exists. The value NULL can be tested, while an invalid pointer cannot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.