Reputation: 3
So, I have an assignment that I need help on. I am given the code for a function called foo() and a function called recover(). I am unable to alter the code for foo, and recover cannot have any arguments, and returns nothing.
The goal of this is to have recover grab the local variables from foo and print them out.
Example:
long foo(long a, long b, long c, long d, long e){
long x, y, z;
if(e < 0)
{
recover();
return a;
}
//do various things with a, b, and c, and store in x, y, and z respectively
return foo(x,y,z,d+1,e-1)+a+b+c+d+e;
}
void recover(void)
{
//What goes here to get the values?
}
What recover() is supposed to do is get the a,b, and c value from EACH call of foo() and print it out. I also know that global variables aren't allowed for this problem.
Thanks for any assistance with this problem.
Upvotes: 0
Views: 108
Reputation: 98398
Warning: the following code is highly compiler/architecture dependent and non-compliant. Use it at your own risk.
Local variables are stored in the stack, so you can get to the local variables of the parent function by just declaring a local variable yourself and moving around.
First add some easy-to-spot values to your variables (you'll remove them later)
long foo(long a, long b, long c, long d, long e){
long x=11111, y=22222, z=33333;
...
Probably you are using a PC, so your stack grows down and your targets are up the stack. Just look around until you find them:
void recover(void)
{
long p;
long *q = &p;
for (int i=0; i < 20; ++i)
{
printf("%d -> %ld\n", i, q[i]);
}
}
Or you can use a debugger, of course!
Upvotes: 2
Reputation: 224147
Sounds like a stack hacking exercise.
Try defining a local variable, taking the address, then modifying that address to go down the stack (either adding or subtracting, depending on your machine) until you end up pointing to the variables in the calling function.
This is very system dependent, so you'll need to do some playing around it figure it out. I'd suggest calling foo
with a known set of arguments and looking specifically for those values to make sure you're looking in the right place. Once you figure that out, you'll have the values for any call to foo
.
Upvotes: 0