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;
}
The following program does not crash:
int main()
{
float* sample;
*sample = (float)1;
return 0;
}
sampleis 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: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.