c++cfunction-callmemory-address

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?


Solution

  • 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();