wattbatt
wattbatt

Reputation: 477

Does a freed memory set pointers referencing to it to null?

Imagine I have a struct for a linked list:

struct node{
     int data;
     struct node* next;
     struct node* prev;
};

I free the last node; does the next pointer of the node before it become NULL automatically?

Because I noticed I didn't do it in a program but everything runs fine..

Upvotes: 1

Views: 57

Answers (4)

Kevin Boone
Kevin Boone

Reputation: 4307

You certainly shouldn't rely on any memory allocated by malloc() to get zero'd when you call free() on it. Certainly you shouldn't expect any pointers to that memory that exist elsewhere in your program to get zero'd.

It's worth running a program under valgrind or similar, to detect cases where a program works by a fortunate coincidence.

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60058

free can't zero its pointer argument in the caller because the pointer argument is taken by value (copy).

void free(void *ptr);

You can't have a function that'd do it while remaining as generic as free, because free will free not just a pointer to void but any other pointer to a non-qualified type (=any other pointer that will implicitly convert to void *).

If you want such zeroing, for security or other reasons, while retaining frees genericity, you can wrap free in a macro.

Example:

#include <stdlib.h>
#include <assert.h>
#define FREE(Pp) (free(*(Pp)),*(Pp)=NULL)
int main(void)
{
    char *m = malloc(1);
    if (!m) return 1;
    FREE(&m);
    assert(!m);
}

Upvotes: 0

0___________
0___________

Reputation: 67476

void free(void *ptr);

function prototype shows that it is not possible to set any value to the pointer ptr.

So the the stored reference will be the same as before the call, but it will reference the invalid memory location. This kind of pointers are called "dangling pointers". If you use this pointer it is an Undefined Behaviour.

Program invoking an UB may behave any way including the correct observable behaviour, but it is incorrect.

You need to make sure that you do not use dangling pointers.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249123

No.

As for why your program appeared to run OK even if you forgot to reset a pointer, it could be you just got lucky.

Upvotes: 2

Related Questions