Created
February 12, 2014 16:24
Another reason I dislike C++ for teaching introductory programming.... this works
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
class BadActor { | |
public: | |
BadActor() { | |
this->value = 5; | |
} | |
int getValue() const { | |
return value; | |
} | |
int get5() const { | |
return 5; | |
} | |
private: | |
int value; | |
}; | |
int main(int argc, char* argv[]) { | |
BadActor* actor = NULL; | |
// This line will result in a crash (actually on line 11) | |
//std::cout << "getValue: " << actor->getValue() << std::endl; | |
// This line doesn't crash | |
std::cout << "get5() = " << actor->get5() << std::endl; | |
} |
Actually, one more on that. If you make the member functions virtual (which is what they would be anyway in Java and the like) you get the expected segmentation fault. So it's not quite as bad as it seems at first. But still rather weird.
Right. W/ the non-virtual version the function call is statically bound, the this parameter is set to 0x0, but since it is never deferenced, no crash occurs.
With the virtual function, the function call must use dynamic dispatch, which fails in the lookup table.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would guess (in first approximation) that constant propagation does this. What's funny is that -O0 doesn't seem to switch off constant propagation. Also if you say "value + 5 - value" in get5() it still works. I tried it with g++ but it would be nice to know what clang does.