-6

I have this piece of code working just fine. Statement in if is true which leads me to printing TRUE. However when I remove the content of else statement, this gives me segmentation fault, even if it doesn't execute (still prints TRUE).

Does anybody have any idea why whould it be that way?

if(parser->checkToken(Token::Type::Int)) {
        std::cout << "TRUE" << std::endl;
        parser->scanner->getToken().getNumber();
        parser->advance();
} else {
        std::cout << "FALSE" << std::endl;
        parser->requireToken(Token::Type::String);
}

p.s. parser is unique_ptr

Pari
  • 458
  • 2
  • 6
  • 15

3 Answers3

1

No, code which doesn't execute can't cause a segmentation fault.

Some other code (executed before the code you have shown) will be the cause.

The other code is exhibiting undefined behaviour (as per the meaning of "undefined" in the C++ standard), and overwriting some area of memory it shouldn't. Removing the else block from your code can cause an implementation (compiler, linker, etc) to restructure how your program and data it uses is laid out in memory (e.g. where code and data are located in memory). That can, in turn, change the effects of your offending code overwriting memory (e.g. it changes whether the overwritten memory is being used to store a variable, or it is some area of memory that your operating system deems your program should not access).

Peter
  • 35,646
  • 4
  • 32
  • 74
1

Without seeing the complete code it is hard to tell, but my guess would be that

parser->scanner->getToken().getNumber();
parser->advance();

(or other code that is not attached here) has some sort of undefined behavior related to it and it is just a matter of luck that you are experiencing segmentation fault with the else section (yes, you are lucky in that regard. Think about what would have happened if you were unable to reproduce it).

Try and see what scanner, getToken(), and getNumber() do in their implementation and locate any operation that may lead to undefined behavior (Maybe getToken() returns a reference to an object that is initialized inside the function?).

Eylon
  • 51
  • 3
0

Sure it can.

Adding/subtracting code, and so it's associated data, moves stuff around in memory to different places, even if, in one case, the code not actually executed itself.

If your code has undefined behaviour, the above can switch the operation of your process between 'working', crashing, nasal demons etc.

ThingyWotsit
  • 366
  • 2
  • 4