为什么这个程序总是崩溃

Why does this program keep crashing

本文关键字:崩溃 程序 为什么      更新时间:2023-10-16

执行时崩溃:

#include <iostream>
int main ()
{
    if(main());
    return 0;
}

为什么?

它崩溃当然是由于Stackoverflow,因为没有终止条件,但从技术上讲,C++编译器允许不编译它,因为在c++中:

main() cannot be called from within a program.
The address of main() cannot be taken.
The main() function cannot be overloaded.

标准规定:

C兼容性附件

3.6
Change: Main cannot be called recursively and cannot have its address taken
Rationale: The main function may require special actions.
Effect on original feature: Deletion of semantically well-defined feature
Difficulty of converting: Trivial: create an intermediary function such as mymain(argc, argv).
How widely used: Seldom

ISO/IEC 14882:2003 (E) 3.6.1 (3)

函数main不能在程序中使用(3.2)。 main的链接(3.5)是实现定义的。将main声明为内联或静态的程序是错误格式的。不保留名称main。[示例:成员函数、类和枚举可以称为main,其他命名空间中的实体也可以称为main。])

根据站点名称,您正在导致堆栈溢出。

每次你的程序执行if语句时,它都会在堆栈上放一些信息,以便它可以返回。然而,程序将继续重复此操作,直到耗尽空间,导致堆栈溢出。

如果main函数调用main函数,则可以无限深度嵌套。然而,每个嵌套级别都需要更多的内存。由于这个过程永远不会结束,您最终会耗尽可用内存(确切地说,是堆栈的内存,其数量级为几兆字节,实际上有很多函数调用)。然后操作系统终止该进程。