Why are stackoverflow errors chaotic?

后端 未结 7 822
醉话见心
醉话见心 2021-01-12 11:29

This simple C program rarely terminates at the same call depth:

#include 
#include 

void recursive(unsigned int rec);

int ma         


        
7条回答
  •  隐瞒了意图╮
    2021-01-12 12:24

    Your recursive call is not necessarily going to cause undefined behaviour due to stackoverflow (but will due to integer overflow) in practice. An optimizing compiler could simply turn your compiler into an infinite "loop" with a jump instruction:

    void recursive(int rec) {
       loop:
        printf("%i\n", rec);
        rec++;
       goto loop;
    }
    

    Note that this is going to cause undefined behaviour since it's going to overflow rec (signed int overflow is UB). For example, if rec is of an unsigned int, for example, then the code is valid and in theory, should run forever.

提交回复
热议问题