我从那里的地址写了这段调用函数的代码:
$ 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)();
这将正确运行测试函数。
关于从命令行中的地址调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211377/