3

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?

bohanl
  • 1,885
  • 4
  • 17
  • 33
  • 1
    This sounds like the sort of thing I'd consider a bug. I just tested it in 5.3.0 and it does not misbehave. Is upgrading an option? If not, you might want to address it with the developers. –  Apr 24 '16 at 01:11
  • No, upgrade is not an option for me – bohanl Apr 26 '16 at 04:06
  • By any chance, have you cast this struct to some other pointer type outside this function? I'm wondering if this could be some form of strict aliasing issue. It's really the best idea I have beyond "compiler bug". Perhaps try `-fno-strict-aliasing`. –  Apr 26 '16 at 05:24
  • 1
    Is this related to the bug we reported here, we always see crashes when using wxWidgets library building with GCC's O2 option, see: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71867 – ollydbg23 Oct 17 '17 at 00:17
  • 1
    Please provide [MVCE](https://stackoverflow.com/help/mcve), the code you provide is not enough to reproduce the problem. – yugr Nov 09 '18 at 06:01
  • Any resolution on this? – copper.hat Apr 28 '22 at 18:03

0 Answers0