Reputation: 27
I was given an exercise to debug a short linked list program, and while I've fixed it to have it behave correctly both with and without the debugger, there is a scenario which I can't wrap my head around from when I was debugging.
The following code fragment traverses and displays the contents of the linked list.
while ( p_itr != NULL )
{
cout << p_itr->val << endl;
p_itr = p_itr->p_next;
delete p_itr;
}
Now, here's the strange thing: when I delete p_itr (pointer to the head of the list), shouldn't I lose the linkage to the rest of my list or dereference invalid memory during the subsequent iteration?
When I run the program normally, it displays all the linked list elements perfectly fine and returns normally (doesn't hang) -- when I use the debugger it gets stuck in an infinite loop, printing a pattern of irrelevant values.
For example, when I add the elements 2, 2, and 2 to the list:
Output: 2 2 2
2 14166872 14166808 14161464 14155968 14167352 14166872 14166808...
Why does the normal program execute successfully? But I my main question is, why does the debugger fall into an infinite loop with these values and the normal program doesn't?
I am using Code::Blocks 16.01.
Upvotes: 1
Views: 173
Reputation: 311088
This code snippet
while ( p_itr != NULL )
{
cout << p_itr->val << endl;
p_itr = p_itr->p_next;
delete p_itr;
}
has undefined behaviour because except the first iteration of the loop there is access to the already deleted object.
It is not clear why the nodes are deleted when the list is outputed. Nevertheless the loop should look at least like
while ( p_itr != NULL )
{
cout << p_itr->val << endl;
auto tmp = p_itr;
p_itr = p_itr->p_next;
delete tmp;
}
Upvotes: 1