以下程序使用 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;
你的第二个程序仍然是错误的,即使它没有崩溃。取消引用未指向有效对象的指针会导致未定义的行为。结果可能是您的程序崩溃,内存中的一些其他数据被覆盖,您的应用程序似乎继续正确运行,或任何其他结果。您的程序今天可能运行良好,但明天运行时可能会崩溃。
我是一名优秀的程序员,十分优秀!