[Solved] Why does my C++ program crash when I forget the return statement, rather than just returning garbage?


Forgetting the return value results in the control flow reaching the end of a function. The C and C++ standards both describe this case. Note that main is an exception to this case and is described separately.

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior
in a value-returning function C++11 Draft pg 136

My experience with clang has been that the compiler will treat instances of “undefined behavior” as will not happen and optimize away the paths. Which is legal, since the behavior is undefined. Often clang will instead emit an illegal instruction along the omitted path so that the code will crash if the “impossible” happens, which is likely your case here. In fact, the compiler could then determine that calling DummyFunc() results in undefined behavior and therefore cannot happen, and instead start optimizing away the calling bodies.

gcc is far “friendlier” and tries to generate something nice, such as returning 0.

Note, both compilers are correct and are producing valid code according to the standard.

4

solved Why does my C++ program crash when I forget the return statement, rather than just returning garbage?