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

前端 未结 6 735
天涯浪人
天涯浪人 2020-12-02 13:46

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

相关标签:
6条回答
  • 2020-12-02 13:53

    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.

    0 讨论(0)
  • 2020-12-02 13:57

    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.

    0 讨论(0)
  • 2020-12-02 13:59

    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
    
    0 讨论(0)
  • 2020-12-02 14:02

    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();
    
    0 讨论(0)
  • 2020-12-02 14:05

    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.

    0 讨论(0)
  • 2020-12-02 14:08

    When you need a direct call:

    ((void(*)(void))0x1234)();
    
    0 讨论(0)
提交回复
热议问题