I have a large code that we were using for a long time in our team. But its several weeks that there is a problem with it when it is compiled on my machine. The code is cross compiled for an Intel Atom CPU and ran on an specific machine.
When it is compiled on my computer, unlike anybody else's, it causes a segmentation fault
. The segmentation faults is from inside an if
block that should not be executed:
Settings *s = &Global::getSettings();
std::cout << "Pointer value before if : " << s << std::endl;
if(s != 0)
{
std::cout << "Pointer value after if : " << &Global::getSettings() << std::endl;
.
.
.
}
Global::getSettings()
is as follows:
.
.
.
private:
static __thread Settings* theSettings;
public:
static Settings& getSettings() {return *theSettings;}
.
.
.
__thread Settings* Global::theSettings = 0;
In my test the value of Global::theSettings is not changed and is equal to zero. Output of the upper code snippet is this:
Pointer value before if : 0
Pointer value after if : 0
Question: How can an if
be executed with condition equal to zero?!
P.S.: I am using clang++ to compile the code on a Debian machine.
It is undefined behaviour to store a null pointer in a reference.
So once it is in the reference, the compiler is free to assume the address is non null, and optimize out your null check.
The "success" of other compilers was just one possible symptom of your undefined behaviour.
Do not store or create references to non-objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With