-1

I have one incredible segment crash call stack in C, could anyone help me out?

int function(struct A *a) 
{
    ... some other declare
    struct B *b = a->b;
    int count, len;
    ... some other declare
    struct C *c = b->c;  /* not crash here */
    ....some other decalre

    if (b->e) { /*crash log indicate b is NULL and crash here,first line instrucment code*/
    .....
    }
    ....
}

My question is why the crash did not happened at the struct C *c = b->c.

GCC is the compiler.

Tony

Barmar
  • 741,623
  • 53
  • 500
  • 612
orasy
  • 25
  • 4
  • Have you seen anything that will guarantee a "crash" in documentation? – Eugene Sh. Feb 10 '17 at 23:05
  • 3
    Accessing invalid pointers is Undefined Behaviour. The compiler is not obliged to guarantee a crash as soon as UB is encountered. By definition UB means the behaviour is unpredicatable. – kaylum Feb 10 '17 at 23:05
  • What's an incredible segment? I'd like to know more about these! – Daniel Kamil Kozar Feb 10 '17 at 23:23
  • The code following if (b->e) will use the c. If the b is one null pointer, I think it should crash at the c = b->c , not at the following code, I met such crash before with the same compiler parameter. – orasy Feb 10 '17 at 23:29

1 Answers1

0

The compiler does not guarantee ordered execution of instructions unless there is a data flow dependency. It has numerous optimizations, one of which is data flow optimization.

Also, if you don't use the variable c at all, the compiler will optimize it out of the code (dead code optimization) and you may not see a crash at all (if the rest of the program works fine).

One easy way to understand which optimization is happening is to access the c variable somewhere. Another way is to disable optimizations (-O0 in GCC).

user1952500
  • 6,611
  • 3
  • 24
  • 37