-1

My goal for my program is to rewrite the return address to be return to another function b(). I could reach and rewrite the return address but i couldn't get the address for function which i want to return to b().

int main(){
  a();
}   

int a(){
  int *ret;
  ret=(int*)&ret+2;
  (*ret)=(int)b();  // <<<<<<<< Here is the problem !!!!
}

int b(){
}
Matt
  • 22,721
  • 17
  • 71
  • 112
user986424
  • 11
  • 3
  • What is your goal by doing such weird thing ? – Cédric Julien Oct 09 '11 at 14:56
  • This previous question is a good starting point for using function pointers in C - http://stackoverflow.com/questions/1278841/function-pointer-in-c – tinman Oct 09 '11 at 14:56
  • Any way you skin this cat will result in undefined behaviour, since there is no such thing as "the return address" in the C language standard. – Kerrek SB Oct 09 '11 at 15:04

3 Answers3

1

When you write b(), you're calling the b function. If you want the address of that function, just write b.

*ret=(int)b;

Note that I have no idea if that will do what you want, and it's not proper C - what you're trying to do is not possible in standard, portable C. It depends entirely on your implementation, CPU, and how the compiler will optimize all that code.

Mat
  • 202,337
  • 40
  • 393
  • 406
0

Maybe you should set function a() to return a pointer.

jcm
  • 1,781
  • 1
  • 15
  • 27
0

I think its depend on your compiler, however you should try

int a(){ int *ret; *(&ret+2)=b; }

but with different architectures the return address maybe store in a register that you cannot change it by this way.

lostyzd
  • 4,515
  • 3
  • 19
  • 33