Search code examples
c++null-pointer

Setting pointer to null creates runtime error


I've been looking around and haven't seen a question with a problem as specific as this one.

I'm trying to create a linked list in this program, but I get a runtime error and no build errors when I run it.

Main:

#include <iostream>
#include "LinkedListInterface.h"
#include "LinkedList.h"
#include <fstream>

int main(int argc, char * argv[])
{
    ifstream in(argv[1]);

    LinkedList<int> myIntList;
}

LinkedList class:

#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <string>
#include <sstream>

using namespace std;

template<typename T>
class LinkedList : public LinkedListInterface<T>
{
public:
    LinkedList()
    {
        head->next = NULL;
    }
private:
    struct Node
    {
        T data;
        struct Node *next;
    };
    Node *head;
};

I have assured that the problem is not with an out-of-bounds error on argv[1], and removing any of the statements in LinkedList() or main() makes the program run smoothly.


Solution

  • You have to construct head before invoking head->next = NULL. But this would mean that there is an empty node in the list when you create it.

    template<typename T>
    class LinkedList : public LinkedListInterface<T>
    {
    public:
        LinkedList()
        {
            // At least do this
            head = new Node();
            head->next = NULL;
    
            // The best idea is to do below:
            // head = null;
        }
    private:
        struct Node
        {
            T data;
            struct Node *next;
        };
        Node *head;
    };