The following is an example code given at Purdue University CS class. I have done very little change to original, for debugging purposes. You can see the original code at https://www.cs.purdue.edu/homes/cs240/lectures/Lecture-19.pdf. The problem i am facing is described below the code piece.
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <string.h>
int a(char* str, jmp_buf aenv) {
int i;
i = setjmp(aenv);
// i ++; i--;
printf("In func a: str = %s, i=%d\n", str, i); #crash causing printf
return i;
}
int b(int j, jmp_buf benv) {
printf("In func b: j= %d\n",j);
longjmp(benv, j); # segfault crash happens here, only if printf is present
}
int main(int argc, char** argv) {
jmp_buf main_env;
char *arr;
arr = (char*) malloc(100);
strcpy(arr, "As if called From main");
if ( a(arr, main_env)) {
printf("In main: a() returned non-zero\n");
exit(EXIT_SUCCESS);
}
b(3, main_env);
int i=1;
i++;
printf("In main: end \n");
return (EXIT_SUCCESS);
}
The platform is Netbeans IDE 7.3 and cygwin 1.7 (latest) in Windows XP. When i run this program the output is
In func a: str = As if called From main, i=0
In func b: j= 3
When i step through the debugger, i see the crash at call to longjmp(). The program runs, but gives unexpected behaviour in debugger, if i remove the printf in function a(). If i remove printf and run program, there is no crash and output is
In func b: j=
In main: end
I have read several documents on the web regarding setjmp/longjmp and i am a professional. My expectation was that a call to longjmp() would take the program state & execution to setjmp, which is in another function. This function a(), should return 3 to main. So, the if condition in main() is TRUE and i should see a printout saying "In main: a() returned non-zero". I was not expecting the printout of "In main: end" because control should never reach there, according to my understanding of setjmp/longjmp.
I suspect this could be a debugger problem, because when i step through the program (without printf in function a() ), the debugger reaches upto longjmp in expected way. When the longjmp is executed, the debugger does not stop anywhere - it simply prints "In main: end" and program terminates. I introduced that i++ in main() to see if the debugger would stop at that point, before printing. But Netbeans does not stop there and the whole program finishes fast, when in step into longjmp().
What is the reason for this behavior ? What is the reason for segfault, in the first case (when printf is present in function a() )? Is the stack unwinding in such a way that the pointer 'str' is messed up ? Why ? If anyone has access to a UNIX machine, i would like to see the output from that system and program behavior. Thanks for your comments.