Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump the program execution to a specific address in C?

Tags:

c++

c

I want the program to jump to a specific address in memory and continue execution from that address. I thought about using goto but I don't have a label rather just an address in memory.

There is no need to worry about return back from the jump address.

edit: using GCC compiler

like image 548
Sam Avatar asked Nov 16 '11 20:11

Sam


2 Answers

Inline assembly might be the easiest and most "elegant" solution, although doing this is highly unusual, unless you are writing a debugger or some specialized introspective system.

Another option might be to declare a pointer to a void function (void (*foo)(void)), then set the pointer to contain your address, and then invoke it:

void (*foo)(void) = (void (*)())0x12345678;
foo();

There will be things pushed on the stack since the compiler thinks you are doing a subroutine call, but since you don't care about returning, this might work.

like image 116
Randall Cook Avatar answered Sep 28 '22 02:09

Randall Cook


gcc has an extension that allows jumping to an arbitrary address:

void *ptr = (void *)0x1234567;  // a random memory address
goto *ptr;                      // jump there -- probably crash

This is pretty much the same as using a function pointer that you set to a fixed value, but it will actually use a jump instruction rather than a call instruction (so the stack won't be modified)

like image 34
Chris Dodd Avatar answered Sep 28 '22 04:09

Chris Dodd