I have the following code excerpt (extract from a big project), when compiled using gcc 4.9.3
with -O2
or -O3
, it crashes when it tries to dereference s
inside the if
block (s->someField
) because s
is a NULL
pointer.
By disassembling this code in gdb, I noticed that the null check is actually optimized out by the compiler, which explains the crash. I googled a bit and found there is an option -fno-delete-null-pointer-checks
supposed to solve this problem, but it behaves the same after I compiled the code with this option.
void someFunc(struct MyStruct *s)
{
if (s != NULL)
{
cout << s->someField << endl;
delete s;
}
}
This doesn't break in gcc 4.7.2
.
Another data point is, if I change the code to the following, it works perfectly fine in gcc 4.9.3
. In gdb, it looks like the NULL
check is not optimized out in this case.
void someFunc(struct MyStruct *s)
{
if (s == NULL)
{
return;
}
cout << s->someField << endl;
delete s;
}
Although I know that I can change the code to make it work, but it is a big project and there is no way for me to change similar cases everywhere, is there some other compiler flags to switch off the compiler optimization for null check?