C++ 指针回溯的分段错误

C++ Segmentation fault from pointer backtrace

本文关键字:分段 错误 回溯 指针 C++      更新时间:2023-10-16

我目前遇到一个 seg 错误,它从我认为是 main 的一行开始,在 gdb 中进行回溯后,我基本上可以查明它,但我不确定需要更改什么。 以下是我按顺序看到它的地方:

主要第一:

DeckOps *deck = new DeckOps(filename);

我相信是导致它的线,回溯还包括

class DeckOps{
 public:
  DeckOps(string filename);
  ~DeckOps();
 private:
  dlist *deck;
}

然后是.cpp文件

DeckOps::DeckOps(string filename){
  ifstream inF;
  inF.open(filename.c_str());
  if (inF.fail()){
    cerr << "Error opening file" << endl;
    exit(1);
  }
  int deckcount = 28;
  int card;
  for(int i = 0; i <= deckcount; i++){
    inF >> card;
    deck->insertRear(card);
  }
  inF.close();
}

然后最后是最后一个地方

void dlist::insertRear(int d){
  LinkNode *link = new LinkNode();
  int *nd = new int();
  *nd = d;
  link->data= nd;
  if(first == 0){
    first = last = link;
    return;
  }
  last->next = link;
  link->prev = last;
  last = link;
}

DeckOps::DeckOps中,行

deck->insertRear(card);

可能导致段错误。 deck是一个指针,但你从不将其初始化为任何东西(如deck = new dlist或其他什么),所以它指向内存中的一个随机位置(或初始化为0,具体取决于你的编译器),并且你试图使用它指向的随机内存(或取消引用NULL指针,同样取决于你的编译器), 导致段错误。您需要在构造函数的顶部执行此操作,然后才能使用它。

如果您修复了它并且它仍然有一个段错误,那么它首先有多个问题,可能在dlist代码中的某个地方。