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

Solution 1:

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

Solution 2:

Yes - you're describing a function pointer. Here's a simple example;

int (*func)(void) = (int (*)(void))0x12345678;
int x = func();

It probably won't work between processes - in most operating systems, processes don't have access to each other's memory.

Solution 3:

When you need a direct call:

((void(*)(void))0x1234)();

Solution 4:

All previous answers are nice but much too long:

int i = ((int (*)(void))0xdeadbeef)();
//                      ==========     --> addr of the function to call
//        =============                --> type of the function to call
//       =========================     --> ... we get a ptr to that fct
//      =============================  --> ... and we call the function