问题描述
以下程序使用g ++编译,但在运行时崩溃:
The following program compiles with g++ but then crashes upon running:
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
is never initialized to point to an object, so when you dereference it, your program crashes. You need to initialize it before you use it, for example:
float f;
float* sample = &f;
*sample = (float)1;
您的第二个程序仍然错误,即使它不会崩溃。取消引用不指向有效对象的指针会导致未定义的行为。结果可能是您的程序崩溃,内存中的一些其他数据被覆盖,您的应用程序出现继续正确运行,或任何其他结果。您的程序可能会在今天看起来运行良好,但在您明天运行时会崩溃。
Your second program is still wrong, even though it does not crash. Dereferencing a pointer that does not point to a valid object results in undefined behavior. The result could be your program crashing, some other data in memory getting overwritten, your application appearing to continue to run correctly, or any other result. Your program could appear to run fine today but crash when you run it tomorrow.
这篇关于微小的崩溃程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!