c++程序在读取NULL引用时崩溃

C++ program crashes upon reading NULL reference

本文关键字:引用 崩溃 NULL 读取 程序 c++      更新时间:2023-10-16

这是c++中的一个链接结构。这里的所有变量和对象都应该有定义好的地址。但是,执行结果却不是这样。

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct LineData {
    int ID;
    char name[33];
    LineData *next;
};
class Line {
    private:
        LineData *pointerHead;
        LineData *pointerToTail;
        int numObjects;
    public:
        Line();
        ~Line();
        void enterLine(int ID, char *data);
        void enterLine(LineData *lindat);
        LineData *exitLine();
        int count();
};
Line::Line() {
    pointerHead = NULL;
    pointerToTail = NULL;
    numObjects = 0;
    /*pointerHead = NULL;
    pointerToTail = NULL;*/
}
/** Puts an item into the line. **/
void Line::enterLine(int ID, char *data) {
    LineData *temp;
    cout << "Inner sanctums called.n";
    temp = new LineData;
    temp->ID = ID;
    strcpy(temp->name, data);
    temp->next = NULL;
    cout << "Temp created.nn";
    //cout << "pointerHead is... ... " << pointerHead << "!n"; Not going to work!
    /* Insert into the Line */
    if(pointerHead != 0) {  /* Insert as first in this Line/You shall not pass! Program will not let you pass! BOOM! Crash! */
        cout << "If tried.n";
        pointerToTail->next = temp;
        pointerToTail = temp;
    }
    else /* Insert at Tail of the Line */
    {
        cout << "pointerHead == NULL. What are you going to do about it?n";
        cout << temp->ID << "n";
        pointerHead = temp;
        pointerToTail = temp;
        cout << "Inserted into Line!n";
    }
}
/** ......
    ......
  ..........
  ..........
    ...... **/

正常编译。

int main() {
    Line *GeorgiaCyclone;
    Line *GiletteIce; // Shaved Ice.
    Line *WoodenMagic;
    Line *SteelCityNinja;
    Line *Egbe; // Hawk.
GeorgiaCyclone->enterLine(4, "Preston");
Egbe->enterLine(2, "Felix");

return 181;
}

每一行的地址在创建时被设置为NULL。使用this没有什么区别。怎么会发生这种事呢?如何缓解这场危机?

Line *GeorgiaCyclone;

创建一个指向Line的指针,但没有创建一个Line供它指向。您需要为它分配一个Line的地址:

Line *GeorgiaCyclone = new Line

更好的是,您可以在main():

中完全避免使用指针。
Line GeorgiaCyclone;

同样适用于您在main()中声明的所有其他Line*

未初始化的非静态局部变量具有不确定的值,并且实际上看起来是随机的,并且很少等于空指针。

对未初始化的指针解引用,或者实际从中读取任何未初始化的变量,会导致未定义行为

我所说的变量当然是你的main函数中的变量。


在c++中,你不应该使用NULL作为空指针;使用nullptr(首选,但仅适用于c++ 11和更高功能的编译器)或0。在c++中,NULL是一个宏,它只扩展到0

你应该总是初始化指针,否则行为是未定义的…如果你想让指针为NULL,你必须将它初始化为NULL。然而,解引用NULL指针仍然是未定义的行为,但至少您可以检查它是否为NULL。养成初始化所有东西的习惯是有益的。

Line *GeorgiaCyclone = NULL;    
if(GeorgiaCyclone!=NULL)GeorgiaCyclone->enterLine(4, "Preston");
else{//some code that alerts you to the fact that you have null pointers, perhaps a message box?
}

如果你忘记分配一个指针,你的程序将不会崩溃。