0

In my code I had this line:

f(t->a, t->b, destroy(t));

Where f is a function, t is a pointer to a struct and destroy is a function which frees the pointer t and returns NULL. The code compiled and run successfully on some compilers (cc, gcc, clang on OS X and clang on Linux) as I expected - t->a and t->b were evaluated before freeing t. However, when compiling with cc/gcc on Linux I got a segmentation fault, as if I was trying to dereference null pointer. What causes that?

Thanks!

Dunno
  • 3,632
  • 3
  • 28
  • 43

1 Answers1

4

Order of evaluation of arguments of a function call is uspecified. destroy(t) may evaluate first and t will be free and therefore t->a will invoke undefined behavior.

C11: 6.5.2.2 Function calls (p12):

In the function call

(*pf[f1()]) (f2(), f3() + f4())

the functions f1, f2, f3, and f4 may be called in any order. [...]

haccks
  • 104,019
  • 25
  • 176
  • 264