This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug c++/81928] if(!this) optimization leads to possible errors without warnings


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81928

--- Comment #8 from Matthieu Brucher <matthieu.brucher at gmail dot com> ---
In a header:
class Foo
{
public:
  void bar();
};

Inthe corresponding source:

#include <iostream>
void Foo::bar()
{
  if(this)
  {
    std::cout << "Pointer is not null";
  }
  else
  {
    std::cout << "Pointer is null, this should not happen, undefined behavior";
  }
}

in main.cpp

int main(int argc, char** argv)
{
  Foo foo;
  foo.bar();

  Foo* foo2 = nullptr;
  foo2->bar();

  return 0;
}

In debug mode, you get once the Pointer is not null and then the other display,
in optimized mode, you get twice the first one.

What is fundamentally wrong is stated in the standard. It is an undefined
behavior to call a method from a null pointer. So testing this inside a method
is an undefined behavior: https://www.viva64.com/en/w/V668/ or even better
https://www.viva64.com/en/b/0226/ since at the time it is clear that gcc didn't
use this perfectly fine optimization.

Once again, GCC acts on this undefined behavior by setting the comparison to
false in optmized mode, which is perfectly fine. The problem is doing so
_silently_, as I said in my original message. Especially since now GCC acts on
this in a non-classic way.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]