c - 为什么这个带有 "abort()"的 C 程序不会崩溃?

标签 c crash

我正在尝试编写一个崩溃的简单 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 说明如下:

  1. 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 by argv[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/

相关文章:

c - 使用 Address Sanitizer 替代 Valgrind

ios - 在Xcode 7中象征崩溃日志

iphone - iPhone崩溃日志-方法名称是否始终正确?

c - 简单的 C 错误 - #include?

c - 简单的 pic10f204 C 编程

c - 如何从C函数中返回字符数组

ios - 应用程序在 iPhone 上打开之前崩溃

delphi - 如何调试仅在应用程序关闭时发生的崩溃? (德尔福)

java - Activity崩溃生命周期方法——android

java - C 或 Java 的非玩具软件事务内存