【问题标题】:i am always getting segmentation fault [closed]我总是遇到分段错误[关闭]
【发布时间】:2022-01-21 02:41:21
【问题描述】:

我总是在 c++ 中得到 10861 分段错误(核心转储)对不起我来自 java 它总是说 head -> 接下来如何为其分配内存

#include <iostream>
using namespace std;

class Node
{
public:
  int data;
  Node *next;
};

class lisp
{
public:
  Node *head;
  void create(int d)
  {
    this->head->data = d;
    cout << head->data;
  }
  void insert(int d)
  {
    Node *n = head;
    Node *add;
    add->data = d;
    cout << head -> next << endl; 
  }
};

int main()
{
  lisp test;
  test.create(0);
  test.insert(1);
  test.insert(2);
  return 0;
}

【问题讨论】:

  • 指针需要引用有效对象。你永远不会为head(或add)分配任何东西,所以你也不能访问head-&gt;data
  • 我可以想象启用编译器警告也会告诉你同样的情况。
  • 在 C++ 中,您必须在使用变量之前自己初始化它们。
  • 有些人会在关闭编译器警告的情况下编译他们的代码。 Don't be like those people!

标签: c++ memory segmentation-fault allocation


【解决方案1】:

您需要先初始化指针,然后再为其分配一些值。因此,您需要Node *add = new Node(); 才能这样做。并且假设您想将一个新节点附加到列表中,也许您需要跟踪列表的尾部(Node *tail)。每次添加新节点时,都会移动 tail

#include <iostream>
using namespace std;

class Node
{
public:
  int data;
  Node *next;
};

class lisp
{
public:
  Node *head;
  Node *tail;
  void create(int d)
  {
    head = new Node();
    head->data = d;
    tail = head;
    cout << head->data << endl;
  }
  void insert(int d)
  {
    Node *add = new Node();
    add->data = d;
    add->next = NULL;
    tail->next = add;
    tail = add;
    cout << add->data << endl; 
  }
};

int main()
{
  lisp test;
  test.create(0);
  test.insert(1);
  test.insert(2);
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多