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

时间:2019-05-26 14:38:37

标签: c++

我正在用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,但是我的代码有问题。

1 个答案:

答案 0 :(得分:0)

我已根据@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;
  }
}