Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function through its address in memory in c / c++

Given knowledge of the prototype of a function and its address in memory, is it possible to call this function from another process or some piece of code that knows nothing but the prototype and memory address? If possible, how can a returned type be handled back in the code?

like image 449
dtech Avatar asked Jan 18 '12 19:01

dtech


People also ask

Where is the address of a function stored in C?

Address of a function in C or C++ In C or C++, the variables are stored into memory, so we can get their memory addresses. Similarly, the functions also are stored into the memory, so they also have some addresses.

What operator gives the memory address of a function?

The & operator is called the reference operator since it gives us a reference to a variable, its memory address.

Can we get the address of memory by using the function pointer?

Address of a function in C or C++ We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details.


1 Answers

On modern operating systems, each process has its own address space and addresses are only valid within a process. If you want to execute code in some other process, you either have to inject a shared library or attach your program as a debugger.

Once you are in the other program's address space, this code invokes a function at an arbitrary address:

typedef int func(void); func* f = (func*)0xdeadbeef; int i = f(); 
like image 116
sbi Avatar answered Sep 17 '22 12:09

sbi