Bcrx
Bcrx

Reputation: 27

Always getting interesting Segmentation Fault with g++

I am working on simple linked list project, everything works fine except List class destructor. I am trying to delete every Node that list has but g++ throws Segmentation Fault everytime(even for empty destructor). Can someone help me, what is wrong with my code? Thanks!.

My List header;

struct Node{
   double data;
   Node* next;
};

class List{
public:
    List();
    ~List();

    void insertF(double data);
    void printList();

private:
    Node* head;
    Node* currNode;
};

List source file;

#include "List.h"

List::List(){
    std::cout<<"Constructed Linked List";
}

void List::insertF(double dataX){
  
  Node* nn = new Node;

  if(!currNode){
    head = nn;
    nn->data=dataX;
    currNode = nn;
  }else{
    currNode->next = nn;
    nn->data = dataX;
    currNode = nn;
  }


}

void List::printList(){
   Node* walker = head;

   while(walker){
    std::cout<<walker->data;
    std::cout<<"----->";
    walker = walker->next;
   }
}

List::~List(){
   
    Node* currNode = head, *nextNode = NULL;
    while(currNode != NULL){
        nextNode = currNode->next;
        delete currNode;
        currNode = nextNode;
    }
    std::cout<<"sd";

}

Main;

#include "List.h"
using namespace std;


int main(){
  List list;


  list.insertF(3.0);
  list.insertF(4.0);
  list.printList();

}

Even;


List::~List(){
    std::cout<<"sd";

}

Throws segmentation fault. List is always filled so I dont check if head is empty

Upvotes: 1

Views: 65

Answers (2)

MikeCAT
MikeCAT

Reputation: 75062

You invoked undefined behavior by using values of the member variables head and currNode without initialization.

Initialize them like this:

List::List(){
    head = nullptr; // add this
    currNode = nullptr; // add this
    std::cout<<"Constructed Linked List";
}

Or like this:

List::List() : head(nullptr), currNode(nullptr) { // add member initialization list
    std::cout<<"Constructed Linked List";
}

Upvotes: 3

cigien
cigien

Reputation: 60228

You have not initialized currNode anywhere, so when you do:

if(!currNode) {

the first time insertF is called, this use of currNode invokes undefined behavior.

You should initialize all your members like this:

Node* head = nullptr;
Node* currNode = nullptr;

Upvotes: 2

Related Questions