开发者

program crashes sometimes

The following routine is expected to remove the node at the start of a single lin开发者_JAVA百科ked list but it fails sometimes.

void remove_from_front(node *start)
{
    delete start;
    start = start->link;
    print_list(start);
}


There are few problems I can see:

  1. You are freeing the start node and then accessing the freed memory. This is incorrect, it leads to undefined behavior which means anything can happen. In one run it might work and in the next run it might crash.

  2. Your function needs to make changes to the head of the list but it is not making the changes visible to the called function as it is not returning anything and the argument start is passed by value. To fix this either pass the address or reference of the start pointer.

  3. Your function might be called on an empty list, start = NULL. You need to handle that case.

Correct implementation:

void remove_from_front(node **start) {

  // if list is empty..nothing to remove..return.
  if(*start == NULL) {
     return;
  }

  // save the address of the node following the start in new_start 
  node *new_start = (*start)->link;

  // now delete the start node.
  delete *start;

 // new_start is now the new start of the list.
 // And since start was passed by address, the change is reflected in the
 // calling function.
  *start = new_start;
}


Once you delete start, you can't safely use pieces of what start used to point to. That's like letting go of a kite string and expecting to be able to take hold of it again later-- it might work, it might not.


You are deleting start, then trying to dereference it by getting its link member. That will crash because you've just deleted it. You probably want something like this:

node *temp = start;
start = start->link;
delete temp;
print_list(start);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜