Why does “noreturn” function return?

前端 未结 9 1601
执念已碎
执念已碎 2020-12-25 10:51

I read this question about noreturn attribute, which is used for functions that don\'t return to the caller.

Then I have made a program in C.

         


        
9条回答
  •  臣服心动
    2020-12-25 11:21

    As others have mentioned, this is classic undefined behavior. You promised func wouldn't return, but you made it return anyway. You get to pick up the pieces when that breaks.

    Although the compiler compiles func in the usual manner (despite your noreturn), the noreturn affects calling functions.

    You can see this in the assembly listing: the compiler has assumed, in main, that func won't return. Therefore, it literally deleted all of the code after the call func (see for yourself at https://godbolt.org/g/8hW6ZR). The assembly listing isn't truncated, it literally just ends after the call func because the compiler assumes any code after that would be unreachable. So, when func actually does return, main is going to start executing whatever crap follows the main function - be it padding, immediate constants, or a sea of 00 bytes. Again - very much undefined behavior.

    This is transitive - a function that calls a noreturn function in all possible code paths can, itself, be assumed to be noreturn.

提交回复
热议问题