gpt4 book ai didi

c++ - 微小的崩溃程序

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:50 25 4
gpt4 key购买 nike

以下程序使用 g++ 编译,但在运行时崩溃:

class someClass
{
public:
int const mem;
someClass(int arg):mem(arg){}
};

int main()
{
int arg = 0;
someClass ob(arg);

float* sample;
*sample = (float)1;

return 0;
}

以下程序不会崩溃:

int main()
{

float* sample;
*sample = (float)1;

return 0;
}

最佳答案

float* sample;
*sample = (float)1;

sample 从未初始化为指向对象,因此当您取消引用它时,您的程序会崩溃。使用前需要先初始化,例如:

float f;
float* sample = &f;
*sample = (float)1;

你的第二个程序仍然是错误的,即使它没有崩溃。取消引用未指向有效对象的指针会导致未定义的行为。结果可能是您的程序崩溃,内存中的一些其他数据被覆盖,您的应用程序似乎继续正确运行,或任何其他结果。您的程序今天可能运行良好,但明天运行时可能会崩溃。

关于c++ - 微小的崩溃程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3382851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com