3

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
boddicheg
  • 53
  • 1
  • 5
  • 1
    Possible duplicate of [Is a return statement mandatory for C++ functions that do not return void?](https://stackoverflow.com/questions/2784075/is-a-return-statement-mandatory-for-c-functions-that-do-not-return-void) – AMA May 24 '18 at 08:45
  • @AMA yep, that issue very similar with mine. Thanks for the pointing. – boddicheg May 24 '18 at 08:53
  • @AMA But still trying to understand what may happens(in terms of UB) and what cause segfault when program tries to build return value from nothing. – boddicheg May 24 '18 at 08:58
  • @Bathsheba `-S` compiler key would be enough for me? – boddicheg May 24 '18 at 09:02
  • @boddicheg you would have to look at the generated gcc assembly to figure out what really happens. Tried [godbolting](https://godbolt.org/) it? – AMA May 24 '18 at 09:06
  • @Bathsheba Will do. Thanks for a new bookmark. – boddicheg May 24 '18 at 09:10
  • @boddicheg: Asking what happens when what happens is undefined is not really logical. If you want to see what the compiler has done with code that has undefined constructs then check the generated assembly. – Bathsheba May 24 '18 at 09:45

1 Answers1

10

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483