簡體   English   中英

從命令行中的地址調用函數

[英]call function from address in commandline

我從那里地址為調用函數編寫了這段代碼:

$ cat main.c 
#include <stdlib.h>
#include <stdio.h>

int test(){
        printf("%s\n","[*] i'm in test");
        return 1;
}

int main(int argc,char **argv){
        int (*m)();
        m=&test;
        printf("[*] test func addr is: %p\n", m);
        (*m)();
        return 0;
}
$ gcc -o main main.c 
$ ./main 
[*] test func addr is: 0x8048414
[*] i'm in test
$ 

沒問題


但我要運行功能,並在命令行中從argv傳遞地址。

例如,如果函數test()地址為0x222222 ,我想用此命令./main 222222運行程序后, test()函數運行..

我的代碼是:

$ cat main.c 
#include <stdlib.h>
#include <stdio.h>

int test(){
        printf("%s\n","[*] i'm in test");
        return 1;
}

int main(int argc,char **argv){
        int (*m)();
        long conv ;
        int num;
        num=conv=strtol(argv[1],NULL,10);
        printf("[*] argv[1] is: %d\n", num);
        m=&test;
        printf("[*] test func addr is: %p\n", m);
        m=num;
        (*m)();
        return 0;
}
$ gcc -o main main.c 
main.c: In function ‘main’:
main.c:17:3: warning: assignment makes pointer from integer without a cast [enabled by default]
$ ./main 8048444
[*] argv[1] is: 8048444
[*] test func addr is: 0x8048444
Segmentation fault (core dumped)
$ 

但沒有運行!

但是,確實應該使用16,而不是10,因為地址始終是十六進制格式,但是即使參數為10,您的代碼仍可以正常運行。由於這種分配,代碼會產生分段錯誤m=num 這會為m分配一個任意值,而不是測試地址,並且在調用(*m)()會產生分段錯誤,因為m指向無效位置。 您應將最后兩行更改為:

num=m;
(*num)();

這樣可以正確運行測試功能。

內存地址以16為底,而不是以10為底,嘗試更改strtol(argv[1],NULL,10); strtol(argv[1],NULL,16);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM