简体   繁体   English

单链表-C ++-无法解释的运行时错误

[英]Singly Linked List - C++ - Unexplainable run-time error

I wrote the following code, to just create and insert nodes (integer data) into an SLL, in C++. 我编写了以下代码,以在C ++中将节点(整数数据)创建并插入到SLL中。

#include <stdio.h>

class Node
{
    public:
        int data;
        Node * next;
        Node * first;
        Node() {}

        void insert(int dat)
        {
            Node * newnode = new Node();
            newnode->data=dat;
            newnode->next=NULL;
            if(first==NULL)
            {
                first=newnode;
            }
            else
            {
                Node *temp=first;
                while(temp->next!=NULL)
                { temp=temp->next; }
                temp->next=newnode;
            }
        }
};

int main()    
{
    Node * a=new Node();
    a->insert(12);
    return 0;
}

At first, I tried overriding the Node constructor to Node(int dat) and in that I tried doing initialization of every new node (data=dat, next=NULL) that I create in insert. 首先,我尝试将Node构造函数重写为Node(int dat),并且尝试对插入中创建的每个新节点(data = dat,next = NULL)进行初始化。 Insert would be called with a "dat" value from main and it would call the overloaded Node constructor to initialize data to dat and next to NULL. 插入将通过main中的“ dat”值调用,并且它将调用重载的Node构造函数将数据初始化为dat并在NULL旁边。 That led to my program crashing. 这导致我的程序崩溃。

So I took out both default and overloaded constructor and did the initialization of each new element in the insert itself. 因此,我取出了默认构造函数和重载构造函数,并对插入自身中的每个新元素进行了初始化。 My program works fine. 我的程序运行正常。 However, even adding the default constructor (as shown in Line 10 of the code) my program crashes. 但是,即使添加默认构造函数(如代码的第10行所示),我的程序也会崩溃。 Can anyone tell me why this is happening in both cases? 谁能告诉我为什么在两种情况下都发生这种情况?

Thanks. 谢谢。

Your default constructor leaves the data members uninitialized. 您的默认构造函数使数据成员保持未初始化状态。 So this line: 所以这行:

Node * a=new Node();

creates a Node with uninitialized members, leading to problems when you try to add a node. 创建具有未初始化成员的节点,从而在尝试添加节点时导致问题。 When you remove your default constructor, the above line (due to the parenteses in new Node() combined with the fact that the class has no user defined constructors) results in a value initialization of all the members, so the pointers get initialized to NULL, and you get the expected behavior. 当删除默认构造函数时,上一行(由于new Node()的括号以及该类没有用户定义的构造函数的事实)导致所有成员的值初始化 ,因此指针被初始化为NULL ,您将获得预期的行为。

If you had left the parentheses out: 如果您省略了括号:

Node * a = new Node;

The data members would be uninitialized, just as when you had a do nothing default constructor. 数据成员将是未初始化的,就像您拥有“不执行任何操作”默认构造函数时一样。

The correct solution is to fix your default constructor to explicitly initialize all members. 正确的解决方案是修复默认构造函数以显式初始化所有成员。

Node() :data(0), next(nullptr), first(nullptr) {}
Node * a=new Node();

Creates a new node, running its default constructor... 创建一个新节点,运行其默认构造函数...

Node() {}

...which doesn't do much - not even initialise data , next or first . ...没什么用-甚至没有初始化nextfirst data

Consequently, when you call... 因此,当您致电...

a->insert(12);

...and it tries... ...并且尝试...

if(first==NULL)

...it's reading from uninitialised memory, resulting in undefined behaviour. ...它是从未初始化的内存中读取的,导致未定义的行为。 On one run the newly-created object might happen to have a 0 in there, another time it might not, some other time it might just crash trying to read the value. 一次运行时,新创建的对象可能恰好在那里有一个0,另一次可能没有,有时甚至只是试图读取该值而崩溃。 You go on to do other worse things with the uninitialised data. 您还要对未初始化的数据做其他更糟糕的事情。

More generally, when you have such problems I recommend you put std::cerr << xyz << '\\n'; 更一般而言,当您遇到此类问题时,建议您将std::cerr << xyz << '\\n'; statements in to dump out some relevant variables, or trace through in the debugger - you might have seen that the variables had garbage values, then could have started to investigate why, which might have yielded a more focused question here, or perhaps led you to an existing answer.... 语句转储一些相关变量,或在调试器中进行跟踪-您可能已经看到变量具有垃圾值,然后可能已经开始调查原因,这可能在这里产生了更集中的问题,或者可能导致您现有答案...。

initialize member variables in constructor like this 像这样在构造函数中初始化成员变量

Node() {
             data =0;
             first = NULL;
             next = NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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