Dangling Pointers
A dangling pointer is a pointer that points to
memory that has already been free()d.
Dangling pointers are extremely dangerous, because you now have a
pointer to memory that you have released back to the operating system.
For the moment, that memory contains all of the information you had stored
at that location. However, if any new space is dynamically allocated, it will
likely be at the address you have just given up. Now your original pointer
points to some new information that's been stored. Dangling pointers are
especially brutal when working with linked lists.
To illustrate, here is a DestroyStack() function that does free all
of the nodes that are in the stack, but fails to set top to NULL when the
stack is empty. top is now a dangling pointer.
The Buggy Code
void DestroyStack(NODEPTR *topPtr)
{
NODEPTR prev, curr;
prev = NULL;
curr = *topPtr;
while(curr != NULL)
{
prev = curr;
curr = curr -> next;
free(prev);
printf("Just freed the node containing %d\n", prev -> data);
}
}
Let's Push() some items onto a stack. We'll print it out to make sure
the stack actually contains what we pushed. Then we'll call the buggy
DestroyStack() function. top now points to a memory location that has been
freed. If we call PrintStack() and pass it top, the original contents of the
stack will print, because the garbage those memory locations contain is our
old information. If we now create a new node, get a value for its data
portion, and Push() it onto the stack, when we call PrintStack(), we find
a disaster :
Output
The stack is empty
Enter the value of data : 1
Pushing the value, 1
Enter the value of data : 2
Pushing the value, 2
Enter the value of data : 3
Pushing the value, 3
Enter the value of data : 4
Pushing the value, 4
The stack contains :
4 3 2 1
Destroying the Stack
Just freed the node containing 4
Just freed the node containing 3
Just freed the node containing 2
Just freed the node containing 1
Finished destroying the Stack
The stack contains :
4 3 2 1
Enter the value of data : 5
Pushing the value, 5
The stack contains :
5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2
5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2
5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2
5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 4 3 2 5 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