中止陷阱 - 我的代码有问题

abort trap - something is wrong with my code

本文关键字:代码 有问题 我的 陷阱      更新时间:2023-10-16

我正在在C 中开发链接列表。我使用delete时有问题。

我阅读了程序参数中的元素数量。我可以创建它们。我可以列出它们。当我使用delete时,代码不起作用。

我是否必须完全使用delete

#include <iostream>
#include <sstream>
struct element {
  int value;
  element *next;
};
int main(int argc, char **argv) {
  int num;
  std::stringstream ss;
  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }
  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    if( first == NULL ) {
      first = elem;
    }
    elem -> value = i;
    elem -> next = NULL;
    if( current == NULL ) {
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }
  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }
  // removing
  current = first;
  while( current ) {
    delete current;
    current = current -> next;
  }
  delete first;
}

我想要的是打印所有元素。我知道每个new都应伴随delete,但是我的代码中有问题。

我已经根据@yksisarvinen评论修复了我的代码。现在起作用。谢谢!

#include <iostream>
#include <sstream>
struct element {
  int value;
  element *next;
};
int main(int argc, char **argv) {
  int num;
  std::stringstream ss;
  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }
  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    elem -> value = i;
    elem -> next = NULL;
    if( current == NULL ) {
      first = elem;
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }
  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }
  // removing
  current = first;
  while( current ) {
    element *to_remove = current;
    current = current -> next;
    delete to_remove;
  }
}