我正在尝试编写一个崩溃的简单 C 程序。我预计如果不提供输入,下面的一个会崩溃。
#include <stdlib.h>
int main(int argc, char * arg[]){
if (argc < 1){
abort();
}
}
我使用 gcc 编译了这个程序,然后使用 ./a.out 运行它,但没有任何反应,没有崩溃。知道为什么吗?谢谢。
最佳答案
它有效。然而,每当您从 shell 作为 ./a.out
运行它时,它都会有一个参数 - 程序名称。 C 标准(C11 5.1.2.2.1p2 说明如下:
If they are declared, the parameters to the main function shall obey the following constraints:
- The value of
argc
shall be nonnegative. [i.e. >= 0!][...]
- If the value of
argc
is greater than zero, the string pointed to byargv[0]
represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. [...]
即C 标准允许 argc
为 <1(如果它恰好是 0
)。
事实上,至少在 Linux 中可以用零参数运行一个 C 程序,只需一点技巧 - 通过从另一个调用 execv
的程序执行它空参数列表:
中止.c:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char * arg[]){
printf("argc is %d\n", argc);
if (argc < 1){
abort();
}
}
runner.c:
#include <unistd.h>
int main(void) {
char *args[] = { NULL };
execv("./abort", args);
}
然后:
% gcc abort.c -o abort
% gcc runner.c -o runner
现在,如果您直接运行 abort
,您将得到:
% ./abort
argc is 1
但是,对于runner
:
./runner
argc is 0
Aborted (core dumped)
关于c - 为什么这个带有 "abort()"的 C 程序不会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794572/