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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With