Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning To Pointer After Freeing It

Tags:

c++

c

pointers

I am looking at the following code from the book "Programming Interviews Exposed":

bool deleteStack( Element **stack ){
      Element *next;
      while( *stack ){
            next = (*stack)->next;
            free( *stack );
            *stack = next;
      }
      return true;
}

I am not that familiar with C++ or C, so this may be a silly question, but wouldn't assigning something to a pointer after freeing it cause a problem?

like image 362
John Roberts Avatar asked Jan 21 '13 16:01

John Roberts


1 Answers

In your example, *stack is a pointer. It is perfectly safe to free the memory it points to then assign the pointer to a new variable.

The only thing that would be unsafe would be to dereference *stack after freeing it.

free( *stack );
next = (*stack)->next;

would be incorrect as the memory pointed to by *stack has unpredictable content (and may no longer even be accessible to your process) after the free call.

like image 62
simonc Avatar answered Oct 22 '22 17:10

simonc