1

When I call the default constructor for my class LinkedList I attempt to assign values to the head node of the linked list before any other operations occur. I have isolate the error, via debugging, to the instructions in the default constructor. As soon as

    head -> next = NULL;
    head -> RUID = 0;
    head -> studentName = "No Student in Head";

are called the program crashes. This occurs when I call the default constructor in main. Here is my class declaration and my struct declaration along with the default constructor:

struct Node
{
    string studentName;
    int RUID;
    Node* next;
};

class LinkedList
{
private:

    // Initialize length of list 
    int listLength;

public:
    // Head of the list, which points to no data yet
    Node *head;
    LinkedList();
    bool insertNode(Node* newNode, int position);
    int generateRUID(); 

};


LinkedList::LinkedList()
{

    head -> next = NULL;
    head -> RUID = 0;
    head -> studentName = "No Student in Head";

    listLength = 0; 
}

I believe this all of the relevant code to this issue. If someone could shed light on this it would be much appreciated.

1
  • 1
    head must be initialized before all of the others. It's an empty reference at the start of LinkedList::LinkedList. Commented Apr 10, 2016 at 23:09

1 Answer 1

3

LinkedList::head is a Node*, not a Node and you don't initialize it, so the object (binary, in-memory) representation is undefined and is therefore dangerous to dereference.

Change your LinkedList to explicitly initialize the head member. I recommend storing it by-value (as Node) rather than as a heap-allocated value (Node*) for simplicitly, unless you know you'll need to reparent nodes.

Using Node*:

LinkedList::LinkedList() :
    head( Node() ),
    listLength( 0 )
{
    this->head->next = nullptr;
    this->head->RUID = 0;
    this->head->studentName = "No Student in Head";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.