程序在NULL指针对象上崩溃

时间:2016-01-29 13:22:18

标签: c++

我正在尝试这样的代码: -

class test{ 
 int test_int;
 public:
    virtual int show()
    {
        return test_int;
    }
    void set_int(int data){
        std::cout<<"received data "<< data <<endl;
        test_int = data;
    }

};
int main()
{
    test *ptr=new test();
    ptr=NULL;
    ptr->set_int(5);
    return 0;
}

现在我面临的问题是我打印通过set_int函数发送的数据后的程序,但程序在完成函数(set_int)之后崩溃。

我是否在做任何不符合语言标准的错误? TIA。

2 个答案:

答案 0 :(得分:4)

  

我是否在做任何不符合语言标准的错误?

是的,你是。

您不能在不指向该类型的有效对象的指针上调用成员函数。空指针永远不会指向有效对象。

此处的简单修复是删除行ptr=NULL;。这样,ptr在调用成员函数时仍然指向一个对象。这也允许您稍后通过删除指针来修复内存泄漏。作为旁注:避免手动内存管理。

答案 1 :(得分:3)

您有指向testtest*)的指针设置为动态分配的内存,表示该类的实例。
在那之后,你写了“不,我不再需要它了”,你忘记了新分配的记忆的位置 最后,您正在尝试访问地址0上的对象,这是一个无效的操作,会导致运行时错误。

你可能打算这样做

int main()
{
    test *ptr = new test();
    ptr->set_int(5);
    // ptr = NULL; // wont free the memory allocated by new
    delete ptr; // memory deallocation
    ptr = NULL; // now we can safely forget that address (which is now invalid anyways)
    return 0;
}