The following short program is obvious wrong (it's taken from the book "How Not
To Program In C++" by Steve Oualline, p.15):

int main()
{
    // An array for the squares
    int array[5];

    int i;  // Index into the array

    for (i = 1; i <= 5; ++i) {
        array[i] = i*i;
    }

    for (i = 1; i <= 5; ++i) {
        std::cout << i << " squared is " <<
            array[i] << '\n';
    }
    return (0);
}

But the program gives the (correct) result:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

when run in Eclipse with cygwin?

One possible effect of undefined behavior is producing the expected result. That's why it's so difficult to explain to someone whose program is working that it's broken and wrong.

You say obviously wrong. In what way? Does the book describe why this is considered bad (or undefined) behavior?

You say obviously wrong. In what way?

It is obviously wrong, and undefined, though I'm not sure the book specifies "undefined". Look at the size of the array, then look at the loops.

Accessing arrays doesn't necessiarly have to throw out of bounds exception, at least I don't think that is a standard requirement. Are you in debug mode? Try running it on release mode and see if it throws an exception or crashes?

It is obviously wrong,

Yes, I got that. That is why I mentioned the undefined behavior. My point was to make the op think about what was going on and explain it as an exercize in working out the problem.

My point was to make the op think about what was going on and explain it as an exercize in working out the problem.

That's a pointless exercise when the book explains what the problem is and why it's a problem. The question was why does the code appear to work correctly when it's provably wrong? It's been a while since I've read that book, but I don't think the author went into detail about how undefined behavior includes expected results. Actually, if I recall correctly, he made some pretty egregious assumptions about the environment.

Thanks. The answer in Oualline's book is: "C++ uses zero-based indexing. So for array[5] the valid elements are: array[0], array[1], array[2], array[3], array[4]. The programmer, however, uses the elements 1-5. There is no array[5], so the program modifies random memory, causing the memory corruption".
Eclipse doesn't throws an exception or crashes. CodeBlock gives the wrong answer: array[5]=5, but the other values array[1],...,array[4] are correct. Strange. As Deceptikon says: One possible effect of undefined behavior is producing the expected result ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.