C++ 指针回溯的分段错误
C++ Segmentation fault from pointer backtrace
我目前遇到一个 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
代码中的某个地方。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?