You will have to know how a stack frame is implemented on your system. I don't know if it is the same for all (or most) x86 systems, but from looking at
this article on wikipedia it looks like it could be this:
+==========================+-+
| locals for function() | |
+==========================+ |
| return address | --> stack frame for function()
+==========================+ |
| parameters for function | |
+==========================+-+
I did some toying around with C, and came up with this:
#include<stdio.h>
void somefunct();
void anotherfunct();
int main(){
somefunct();
printf("returned to main!\n");
return 0;
}
void somefunct(){
int *ptr = (int*)&ptr + 2;
*ptr = (int)&anotherfunct;
}
void anotherfunct(){
printf("I win!\n\n");
}
this prints the output:
~/c/t $ ./retaddr
I win!
Segmentation Fault
~/c/t $
The segmentation fault is because the stack is set up to return to main, and then return to the system once main completes. But since the return address is bashed to returned to yet another function, that function get's main's call stack. I have no idea what this does, but I'm assuming it is bad.
I had to play with the magic number (which turned out to be 2) for a bit, but I'm not exactly sure about why 2. I could play with it more and find out just how the stack frame looks, but I'll leave that up to you.
For fun, compile my code on your machine and see if you get identical output. Try it on a windows box. The behavior of this sort of thing depends heavily on the compiler and system.
I would play with this more but it's 2AM and time to get some rest.