为何调用abort()的C程序未崩溃?技术求助
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:
argccounts all arguments passed to the program, including the program's own path/name.argv[0]is always the executable you're running—this is whyargccan never be 0.- Any extra arguments you pass (e.g.,
./a.out test 123) start atargv[1], which increasesargcby 1 for each one.
内容的提问来源于stack exchange,提问作者zell

