为什么这个程序会崩溃

时间:2011-04-22 19:07:00

标签: c++ visual-c++

执行时崩溃:

#include <iostream>

int main ()

{
    if(main());
    return 0;
}

为什么?

4 个答案:

答案 0 :(得分:11)

由于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

答案 1 :(得分:2)

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

  

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

答案 2 :(得分:0)

根据您导致堆栈溢出的站点名称。

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

答案 3 :(得分:0)

如果main函数调用main函数,则嵌套深度无限。但是,每个嵌套级别需要更多的内存。由于这个过程永远不会结束,你最终会运行可用的内存(确切地说,是堆栈的内存,它的数量级是几兆字节,真的有很多函数调用)。然后操作系统就会终止这个过程。

相关问题