SetJmp / LongJmp: Why does it throw segfault?

The following code summarizes the problem that I have at the moment. My current thread of execution is as follows, and I am starting up in GCC 4.3.

jmp_buf a_buf; jmp_buf b_buf; void b_helper() { printf("entering b_helper"); if(setjmp(b_buf) == 0) { printf("longjmping to a_buf"); longjmp(a_buf, 1); } printf("returning from b_helper"); return; //segfaults right here } void b() { b_helper(); } void a() { printf("setjmping a_buf"); if(setjmp(a_buf) == 0) { printf("calling b"); b(); } printf("longjmping to b_buf"); longjmp(b_buf, 1); } int main() { a(); } 

The above thread of execution creates segfault immediately after returning to b_helper. It is almost as if only the stack stack of the b_helper stack was installed, and the stacks below it are erased.

Can anyone explain why this is happening? I guess this is a GCC optimization that erases unused stack frames or something like that.

Thank.

+6
c ++ gcc segmentation-fault g ++
Sep 04 '09 at 23:22
source share
2 answers

You can only longjmp() back up the call stack. The call to longjmp(b_buf, 1) is that the situation is starting to go wrong, because the stack frame referenced by b_buf no longer exists after longjmp(a_buf) .

From the documentation for longjmp :

Longjmp () routines may not be called after the routine called by the setjmp () routine returns.

This includes a β€œreturn” via longjmp() from the function.

+12
Sep 04 '09 at 23:28
source share

The standard says longjmp() (7.13.2.1 longjmp function):

The longjmp function restores the environment saved by the last call to the setjmp macro in the same program call with the corresponding jmp_buf argument. If there was no such call, or if the function containing the setjmp macro call completed execution in a temporary

with a footnote that clarifies this a bit:

For example, by executing a return statement or because another longjmp call has called, go to the setjmp call in the function earlier in the set of nested calls.

Thus, you cannot longjmp() move forward and backward through the nested sets of setjmp / longjmp .

+5
Sep 04 '09 at 23:30
source share



All Articles