just as a disclaimer this question has to do with a particular assignment I have an I am not asking for anyone to do my homework for me.
So basically I am supposed to implement a way to return directly to main from a function call of a function call.
Part of the stipulations are that we cannot use an assembly language instructions, gcc's asm(), or gcc built ins. After doing a lot of research on this on google I couldn't really find any examples to look at or even the source code for setjmp/longjmp (the purpose of this assignment is to copy those functionalities). I've asked some more older CS students for advice and most couldn't help or told me they are pretty sure it is not possible with the stipulations given. Any advice or pointers (haha) will be appreciated. Even a nudge in the right direction or confirmation that the assignment is not as complicated as I think will be greatly appreciated!
So far my best attempt:
-Use a setjmp function to store the address of where we left off in main (so something like x = foo1(); and pass x into setjmp(x)) and then have foo2 call my longjmp function where in longjmp I'll have the function set a pointer (*p) to my argument and then (*p-1) = address of x in main.
This didn't work but I thought it was the right idea trying change the return address in the call stack since if I understood it correctly, the arguments of the function are directly on top of the return address in the stack.
Here is the code I wrote:
int setjmp(int v);
int longjmp(int v);
int fun1(void);
int fun2(void);
int *add; //using global, not sure if best idea
int main(void)
{
int x = setjmp(x);
foo1();
return 0;
}
int setjmp(int v)
{
add = &v; //used a global variable
return 0;
}
int longjmp(int v)
{
int *p; //pointer
p = &v; //save argument address
*(p-1) = *add; //return address = address in main
return 1;
}
int foo1(void)
{
printf("hi1");
foo2();
printf("hi2");
return 0;
}
int foo2(void)
{
int a;
longjmp(a);
return 0;
}//output SHOULD be "hi1"
//output is currently "hi1" "hi2"
for what it's worth every line I have not commented was given as a skeleton and I cannot change it.
Excuse me in advance if something is off, I am quite new to C. Thank you.