You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何调用abort()的C程序未崩溃?技术求助

Why Your C Program Isn't Crashing When Expected

Let's break down exactly what's going on here and why your program isn't behaving as you intended.

First, let's look at the core issue in your code:

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

The problem is your check for argc < 1. Here's the critical detail you're missing: argc (argument count) is always at least 1, no matter how you run the program. When you execute ./a.out, the operating system automatically passes the program's own name as the first argument (argv[0]), so argc gets set to 1 every single time. That means your if condition will never be true, so the abort() call never runs—hence no crash.

How to Fix It

If you want the program to crash when there are no additional command-line arguments (beyond the program name itself), you need to check if argc < 2 instead. This way, when you run ./a.out without any extra args, the condition triggers and abort() executes as expected.

Here's the corrected code:

#include <stdlib.h>
int main(int argc, char *argv[])
{
    // Check for no extra arguments instead of no arguments at all
    if (argc < 2)
    {
        abort();
    }
    return 0;
}

Now when you compile and run ./a.out, you should see output like this:

Aborted (core dumped)

A Quick Recap on argc

To make sure this sticks:

  • argc counts all arguments passed to the program, including the program's own path/name.
  • argv[0] is always the executable you're running—this is why argc can never be 0.
  • Any extra arguments you pass (e.g., ./a.out test 123) start at argv[1], which increases argc by 1 for each one.

内容的提问来源于stack exchange,提问作者zell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:00:07