Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't free(p) set p to NULL?

Tags:

People also ask

Does freeing make a pointer null?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

Should you set pointers to null?

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.

What will occur if we call the free () function on a null pointer?

See: man free The free() function deallocates the memory allocation pointed to by ptr. If ptr is a NULL pointer, no operation is performed. When you set the pointer to NULL after free() you can call free() on it again and no operation will be performed.

What happens to a pointer after free?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address. It will not automatically be changed to NULL or anything else.


Any reasons why this can not be standard behavior of free()?

multiple pointers pointing to the same object:

#include <stdlib.h>
#include <stdio.h>

void safefree(void*& p)
{
    free(p); p = NULL;
}

int main()
{
    int *p = (int *)malloc(sizeof(int));
    *p = 1234;
    int*& p2 = p;
    printf("p=%p p2=%p\n", p, p2);
    safefree((void*&)p2);
    printf("p=%p p2=%p\n", p, p2);
    safefree((void*&)p); // safe

    return 0;
}

assignment from malloc demands cast from void*

vice versa:

safefree() demands cast to void*& (reference)