这个程序怎么会在最后一行 (return 0;) 之后崩溃?

How can this program crash after at the last line (return 0;)?

我有一个程序,分成多个文件,有很多代码包含数组、指针、结构等等。

进入正题:这些是我的 main() 方法的最后几行;

   ...
   printf("\nLast line!");
   return 0;
}

我在没有警告的情况下编译了这个程序后,我执行了它,在我的控制台中,我在我的 CMD 中得到了文本:Last line!,然后程序崩溃了(没有响应)。

我经常使用 printf() 来调试我的代码并确定我的代码中程序崩溃的那一行。在这种情况下,我无法理解程序在最后一行代码 之后 崩溃的事实。

我的问题:

注意:我确定我的代码中只有一个 printf("\nLast line!");

could return 0; in the main() function cause a crash?

仅就声明而言,不,它不会导致 崩溃

And is it possible the program crashes due to undefined behavior earlier in my program?

是的。很可能是这样。您在代码中较早的地方调用了 undefined behaviour,如您所知,结果是未定义的。

If so, how can I debug my code?

尝试通过调试器和内存检查器 运行 您的程序,例如 linux 上的 gdb 和 valgrind。此外,请尝试在 tricky 区域的代码中添加断点,并在检查实际值与预期值的同时单步执行调试器。您很可能会发现错误。

也停止使用 printf(); 尝试一个好的调试器,例如(gdb)调试 C 代码更简单、更快