将指针设置为null会导致运行时错误

时间:2019-02-20 03:31:14

标签: c++ null-pointer

我一直在环顾四周,还没有看到一个像这个问题一样具体的问题。

我正在尝试在此程序中创建一个链表,但是运行时出现运行时错误且没有构建错误。

主要:

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

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

    LinkedList<int> myIntList;
}

LinkedList类:

#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;
};

我向您保证,问题不在于argv [1]的出界错误,并且删除LinkedList()或main()中的任何语句都可以使程序平稳运行。

1 个答案:

答案 0 :(得分:0)

您必须在调用head之前构造head->next = NULL。但这意味着创建列表时列表中没有一个空节点。

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;
};