Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if(null) is being executed in a specific computer compiling with clang++

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.

like image 411
Sheric Avatar asked Jan 09 '23 04:01

Sheric


1 Answers

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.

like image 61
Yakk - Adam Nevraumont Avatar answered Jan 14 '23 13:01

Yakk - Adam Nevraumont