0

I had the following code compiled in g++ and it worked.

bool keyExists(Obj key){
    findIn(key,true,false,false,nullptr,nullptr,1,0,0);
}

I compiled it using clang++ and when the program run it froze.

I changed the lines to:

bool keyExists(Obj key){
    return findIn(key,true,false,false,nullptr,nullptr,1,0,0);
    //findIn(key,true,false,false,nullptr,nullptr,1,0,0);
}

and now it works.

I suppose it shouldn't work like that. Is it is a known bug of Clang or a special case?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
George Kourtis
  • 2,381
  • 3
  • 18
  • 28

2 Answers2

5

Your code reaches the end of the function without returning anything.

This is undefined behavior, so the compiler is perfectly correct.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

In C++, if the execution of a function ends without this function having invoked a return statement (and it is not a void function) then the behavior is undefined.

As the name implies, undefined means that pretty much anything can happen. In the case of a missing return statement, the most frequent behaviors are:

  • getting a garbage value, the effect of which depends on how you use it
  • getting a "scrapped" value, that is for some reason you end up with the value of the latest expression of the function which is generally what you wanted

However, there are plenty other possibilities. Notably, an instrumented build could decide to hang or crash (with more or less explanations as to the cause), or the compiler could play "tricks" on you assuming that you upheld your end of the "I shall never write code that exhibits undefined behavior" (an implicit contract you accepted without knowing it) and therefore that this code can never be executed and can be culled entirely.

Hanging is within possibilities.


Now, the real question is did not you get any warning from the compiler? Those are not "chatty" messages, they most often point at real issues!

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722