function returning std::string crashes without return statement, unlike a function returning int without return statement

[亡魂溺海] 提交于 2021-02-19 03:47:09

问题


#include <iostream>
#include <string>
using namespace std;

string
crash()
{

}

int
noCrash()
{

}

int
main()
{
    crash(); // crashes
    // noCrash(); // doesn't crash
    return 0;
}

The function crash(), crashes with Mingw g++ 4.6.2 and the function noCrash() executes with no issues. Why does the function returning string crash without a return statement?


回答1:


Both are undefined behaviors, even noCrash can crash.




回答2:


From standard 6.6.3/2

A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (12.2). 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.




回答3:


A lot of this is undefined, but it arguably helps to understand the practical reasons for such observations - it can help in troubleshooting and even performance and spatial design.

So, in a practical sense, if the function fails to return a value, it's basically failing to set the register or memory where that value will be expected by the caller; it appears to return whatever garbage used to be there. If the return type is int, you've just got yourself a garbage value, but for strings you have a garbage value that's meant to point (directly or indirectly) to the heap memory used by the string to store the textual value and possibly some reference counter or other management data. Later in the program, the calling code will try to deallocate that heap memory by deleting the pointer. Deleting a pointer with a garbage value's quite likely to crash your program.




回答4:


Probably because when you call crash the compiler attempts to destroy a temporary std::string object that was never created.

As both functions have undefined behavior speculation is somewhat futile.



来源:https://stackoverflow.com/questions/11096027/function-returning-stdstring-crashes-without-return-statement-unlike-a-functi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!