Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not returning value from function cause segfault

Found strange behavior that i don't understand:

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;
 }

In this case commented return in subdomainVisits function causes Segmentation fault(use gcc version 7.3.0 (Debian 7.3.0-19) ). Uncommenting fix this problem.

Why it happens?

like image 934
boddicheg Avatar asked Sep 13 '25 18:09

boddicheg


1 Answers

The behaviour of your program as written is undefined.

A non-void function must have an explicit return value on all control paths.

The only exception to this is main, which has an implicit return 0;.

A fair number of compilers will warn you of trivial cases such as the above. Do you not have the warning level set high enough? (Pass -Wall and -Wextra to "turn up" the warning level on gcc.)

Note that the C++ standard does not require a compiler to fail compilation: theoretical computer science (the halting problem) tells us that reachability is impossible to prove.

like image 173
Bathsheba Avatar answered Sep 15 '25 07:09

Bathsheba