函数未返回值导致段错误

问题描述 投票:0回答:2

发现我不明白的奇怪行为:

std::vector<std::string> subdomainVisits(std::vector<std::string> &cpdomains)
{
    // return std::vector<std::string>();
}

int main(int argc, char const *argv[])
{
     std::vector<std::string> data = { "9001 discuss.leetcode.com" };
     auto result = subdomainVisits(data);
     return 0;
 }

在这种情况下,在

return
函数中注释
subdomainVisits
会导致分段错误(使用 gcc 版本 7.3.0 (Debian 7.3.0-19) )。取消注释可以解决此问题。

为什么会发生这种情况?

c++ gcc segmentation-fault
2个回答
10
投票

您编写的程序的行为是未定义

void
函数必须在所有控制路径上具有显式返回值。

唯一的例外是

main
,它有一个隐式的
return 0;

相当多的编译器会警告您诸如上述的小情况。您的警告级别设置得不够高吗? (通过

-Wall
-Wextra
来“调高”gcc 上的警告级别。)

请注意,C++ 标准不要求编译器编译失败:理论计算机科学(停止问题)告诉我们可达性是无法证明的。


0
投票

这是预期的行为。

-Wreturn-type
添加到选项中以防止遇到这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.