views:

176

answers:

3

People often comment that a program can legitimately respond to undefined behavior by deciding to reformat your hard drive. However, in practice undefined behaviors in most languages do something rather unsurprising, for example:

  1. Fail (e.g. crash, throw an exception, or otherwise interrupt execution).
  2. Refuse to compile. Yeah, that one is boring. If it happens, people fix the error and probably don't even contemplate it in terms of undefined behavior.
  3. Pick a specific, somewhat arbitrary choice (mainly when the behavior is undefined because it is ambiguous).

I have yet to see a serious C++ compiler that responds to u = (u++); by reformatting the hard drive. I also have yet to see a case where this assigned the value of u+2 to u, though this would only be a mildly surprising rather than shocking.

Can anyone offer real-world examples where the undefined behavior was incredibly shocking and/or weird?

+4  A: 

On machines without protected address spaces following bad pointer can write on memory belonging to other processes or even the OS and the results really can be bad.

You really can cause arbitrary file corruption when the memory that got scribbled on was disk buffers. And no programmer/compiler maliciousness was needed. It just happened that way.

/ bad experience on Mac System 6

dmckee
+2  A: 

Using uninitialized booleans can have some somewhat surprising results. The code example below outputs "true != true". Undefined variables may be neither true nor false.

#include <string>
#include <iostream>

using namespace std;

namespace {

    inline string stringify(const bool value)
    {
        return (value ? "true" : "false");
    }

    struct Struct
    {
        long l;
        bool u;
    };
}

int main()
{
    Struct s;

    if(true != s.u)
        cout << stringify(true) << " != " << stringify(s.u) << endl;
}

Source: http://mlangc.wordpress.com/2010/07/18/when-true-is-not-true-anymore/

Sibshops
I've seen that kind of painful stuff happen in VB6 when I inadvertently (I think with some sort of C++ function) stuffed a VB6 boolean with a number.
Brian
+6  A: 

Some earlier version of GCC attempted to launch nethack upon finding #pragmas that it did not understand.

Steven Schlansker
According to the page you linked to, this is implementation-defined behavior, not undefined behavior. Close enough, though.
Brian
Sure, but I figured it fit in the spirit of the question, even if maybe not the exact letter :)
Steven Schlansker
I agree, I just felt it was something worth calling attention to.
Brian