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,
*stackis 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
*stackafter freeing it.would be incorrect as the memory pointed to by
*stackhas unpredictable content (and may no longer even be accessible to your process) after thefreecall.