1

This question comes from SetJmp/LongJmp: Why is this throwing a segfault?

When I use debug mode run the code it did crash as expect. But if I use release it will output like this:

1 setjmping a_buf
2 calling b                // loop start
3 entering b_helper
4 longjmping to a_buf
5 longjmping to b_buf
6 returning from b_helper  // loop
2 calling b
3 entering b_helper
4 longjmping to a_buf
5 longjmping to b_buf
6 returning from b_helper
...

As my understanding, longjmp can be considered as return so the stack memory of b_helper will be erased and accessing become illegal. that make the program crash become reasonable. But why it gives different behaviour in release? Looks like return behave as longjmp. So the result in release shall be the right and my understanding is wrong.

Mingw: 5.3

JustWe
  • 4,250
  • 3
  • 39
  • 90

2 Answers2

3

The code in question causes undefined behaviour. The program is incorrect, there is no expected behaviour. You should not expect nor be surprised by any particular output or other behaviour.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • @S.M. answer look reasonable, the code indeed wrong. But it shall give one behaviour because using same compiler(gcc). – JustWe May 17 '18 at 02:18
  • 2
    This is the right answer. Anyone hoping for a segfault reliably should be made to read https://blog.regehr.org/archives/213 to develop a healthy sense of the pitfalls of UB. – Tanz87 May 17 '18 at 02:24
0

Which compiler do you use? If you use g++ compiler, i.e. the programming language is C++, the functions b_helper is inlined into the function b, and the function b is inlined into the function a in the release mode with enabled optimizations. In this case there are no more routings left that call setjmp and return.

273K
  • 29,503
  • 10
  • 41
  • 64