DEV Community

Discussion on: What was the weirdest bug you ever encountered?

Collapse
 
dwd profile image
Dave Cridland

I've been using C/C++ since around 1990 or so. The old problems were usually weird compiler bugs when optimizations went wrong dramatically, from what I can recall. But I was thinking more of cases like this, which tripped me up recently - I'll simplify, of course:

int * p = nullptr; // Start with a NULL pointer.
int & r = *p; // Later on, convert to a reference, probably in a function call.
int * i = &r; // Convert the reference back to a pointer.
if (i != nullptr) { // If it's not NULL
  std::cout << "i is now " << *i << std::endl; // Print it.
}

That code crashes with a segfault trying to deference a NULL pointer. This is because the standard says that if the address of a reference is the NULL pointer, it's Undefined Behaviour. So most modern compilers now choose to optimize away the test, even without optimization turned on...

Thread Thread
 
metalmikester profile image
Michel Renaud

"Undefined behaviour" is hell.