[英]C++ Segmentation fault from pointer backtrace
I am currently getting a seg fault and its starting at what I believe to be a line in main, after doing a backtrace in gdb, I can basically pinpoint it but I am not sure what needs to change. 我目前正在遇到段错误,它从我认为是主行的地方开始,在gdb中执行回溯之后,我基本上可以查明它的位置,但是我不确定需要更改什么。 here are the places I am seeing it in order:
这是我按顺序看到的地方:
First in main: 主要第一名:
DeckOps *deck = new DeckOps(filename);
I believe is the line that is causing it, backtrace also includes 我相信是造成它的那条线,回溯还包括
class DeckOps{
public:
DeckOps(string filename);
~DeckOps();
private:
dlist *deck;
}
and then the .cpp file 然后是.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();
}
and then finally the last place 最后是最后一个地方
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;
}
In the DeckOps::DeckOps
, the line 在
DeckOps::DeckOps
,该行
deck->insertRear(card);
is probably causing the segfault. 可能导致段错误。
deck
is a pointer but you never initialize it to anything (like deck = new dlist
or whatever) so it points to a random location in memory (or is initialized to 0
depending on your compiler) and you're trying to use the random memory it's pointing to (or dereferencing a NULL
pointer, again depending on your compiler), causing a segfault. deck
是一个指针,但您永远不会将其初始化为任何内容(例如deck = new dlist
或其他任何东西),因此它指向内存中的随机位置(或根据编译器初始化为0
),并且您尝试使用随机内存它指向(或再次引用NULL
指针,再次取决于您的编译器),从而导致段错误。 You'll need to do that at the top of the constructor before you can use it. 您必须先在构造函数的顶部执行此操作,然后才能使用它。
If you fix that and it still has a segfault, then it had more than one problem in the first place, probably somewhere in the dlist
code. 如果您修复了该错误,但它仍然存在段错误,那么它首先会出现多个问题,可能是
dlist
代码中的某个地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.