程序有时会崩溃

use*_*385 1 c++ pointers linked-list data-structures

期望以下例程在单个链表的开头删除节点,但有时会失败.

void remove_from_front(node *start)
{
    delete start;
    start = start->link;
    print_list(start);
}
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 8

我可以看到几个问题:

  1. 您正在释放start节点,然后访问释放的内存.这是不正确的,它会导致未定义的行为,这意味着任何事情都可能发生.在一次运行中它可能会起作用,在下一次运行中它可能会崩溃.

  2. 您的函数需要对列表的头部进行更改,但它不会使更改对被调用函数可见,因为它不返回任何内容并且参数start是按值传递的.要解决此问题,请传递start指针的地址或引用.

  3. 您的函数可能会在空列表中调用start = NULL.你需要处理这种情况.

正确实施:

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;
}
Run Code Online (Sandbox Code Playgroud)


Bet*_*eta 5

一旦你delete start,你就无法安全地使用start过去指向的部分.这就像放下一个风筝线,并希望以后能够再次抓住它 - 它可能会起作用,它可能不会.