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

Why this C program with "abort()" does not crash?

我正在尝试编写一个会崩溃的简单 C 程序。如果没有提供输入,我希望下面的崩溃。

#include <stdlib.h>
int main(int argc, char * arg[]){
  if (argc < 1){
    abort();

  }
}

我使用 gcc 编译了这个程序,然后 运行 使用 ./a.out,但是没有任何反应,没有崩溃。知道为什么吗?谢谢。

它不会崩溃,因为 argc 是参数计数,当您使用 ./a.out 执行程序时,argc 的值是 1。所以不用检查

if (argc < 1){ /* 1<1 condition fails */
   abort();
}

检查

if (argc == 1){
    abort();
}

我预计如果没有提供输入,下面的程序会崩溃。 ? 为什么要通过调用 abort() 使其崩溃,exit(0) 是个好主意,它会清理所有内容并正常终止进程。

有效。然而,无论何时你从 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 的程序:

abort.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)