简体   繁体   中英

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. 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

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM