从命令行中的地址调用函数

标签 c gcc

我从那里的地址写了这段调用函数的代码:

$ 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 222222test() 函数运行..

我的代码是:

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

这将正确运行测试函数。

关于从命令行中的地址调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211377/

相关文章:

c - 为什么UDP socket通信不出错?

c - 如何向libnl发送单 channel 扫描请求,并接收相应 channel 的单 channel 扫描完成响应

c - C 中自动 stdout 缓冲区刷新的规则是什么?

c - 除了最后一个之外,所有 #pragma GCC 诊断均被忽略

c++ - gcc优化?漏洞?及其对项目的实际意义

c - 输出原因

c - C 中的强制转换运算符和后缀有什么区别?

gcc - 使用现有的交叉编译器构建 newlib

c - 在 main 中获取 __attribute__ ((constructor)) 函数的值

gcc - 链接器问题 - undefined reference