简体   繁体   English

从另一个函数调用 main

[英]Calling main from another function

I am new to C, so forgive me if this query is basic.我是 C 的新手,所以如果这个查询是基本的,请原谅我。

I want to call main() from another function, and make the program run infinitely.我想从另一个函数调用 main(),并使程序无限运行。 The code is here:代码在这里:

#include <stdio.h>

void message();

int main()
{
    message();

    return 0;
}

void message()
{
    printf("This is a test message. \n");

    main();
}

I expect to see this program run infinitely.我希望看到这个程序无限运行。 However, it runs for some time and then stops suddenly.但是,它运行了一段时间,然后突然停止。 Using a counter variable, which I printed alongside the test message, I found that the statement "This is a test message."使用我在测试消息旁边打印的计数器变量,我发现语句“这是一条测试消息”。 is printed 174608 times after which I get an error message打印 174608 次,之后我收到一条错误消息

Segmentation fault (core dumped)分段错误(核心转储)

and the program terminates.并且程序终止。 What does this error mean?这个错误是什么意思? And why does the program only run 174608 times (why not infinitely)?为什么程序只运行了 174608 次(为什么不是无限次)?

You have stack overflow from infinite recursion.你有无限递归的堆栈溢出。 Make infinite loop in main :main无限循环:

int main()
{
  while (1)
  {
    //...
  }
}

The mutual recursion costs stack space.相互递归会消耗堆栈空间。 If you put the recursion in main() itself, the compiler may recognise the tail recursion , and replace it by iteration.如果将递归放在main()本身中,编译器可能会识别尾递归,并通过迭代替换它。 [for fun and education, don't try this at home, children ...] : [为了好玩和教育,不要在家里尝试这个,孩子们......]:

#include <stdio.h>      

void message(); 

int main()
{
    message();  

    return main();
}       

void message()  
{       
    printf("This is a test message. \n");
}

GCC recognises the tail recursion in optimisation level=2 and above. GCC 识别优化级别=2 及以上的尾递归。 main.s output for gcc -O2 -S main.c: gcc -O2 -S main.c 的 main.s 输出:

        .p2align 4,,15
.globl main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        andl    $-16, %esp
        .p2align 4,,7
        .p2align 3
.L4:
        call    message
        jmp     .L4
        .size   main, .-main
        .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3"
        .section        .note.GNU-stack,"",@progbits

This is not equivalent to while(1) {...} or for(;;) {...} , which give you infinite loops.这不等同于while(1) {...}for(;;) {...} ,它们会给你无限循环。

Every time a function(for example, main() or message() ) is called, some values are pushed into the stack .每次调用函数(例如main()message() )时,都会将一些值压入堆栈 When functions are called too many times, your stack get filled, and finally overflow, giving you a "stack overflow" error.当函数被调用太多次时,你的堆栈被填满,最后溢出,给你一个“堆栈溢出”错误。

Note that this error has nothing to do with this site, although they happen to have the same name :)请注意,此错误与此站点无关,尽管它们碰巧具有相同的名称:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM