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

旧城冷巷雨未停 提交于 2019-11-27 18:10:46

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

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.

When you need a direct call:

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

All previous answers are nice but much too long ;-) :

int i = ((int (*)(void))0xdeadbeef)();

In most OP, every process has its own memory, so you can't.

Sample code: a.c:

#include <stdio.h>

int r() {return 2;}
int main() {
    printf("%p\n",r);
    while(1);
}

b.c:

#include <stdio.h>

int main() {
int a,(*b)();
scanf("%p",&b);
a=b();
printf("%d\n",a);
return 0;
}

this get segmentation fault.

It is definitely possible, but there are restrictions. Each process will have its own block of memory which other processes can't interfere with. Now, you will notice, I wrote it is definitely possible, this is through DLL injection (or code injection).

We can use the typedef keyword to achieve this. Now, I see you've marked the answer as 'Answered' and it seems you've gotten on fine, this is just a notice for anyone else that may be interested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!