środa, 15 lipca 2015

C++ magick

A programmer wrote:

class container;

class IndexOutOfBounds {
    IndexOutOfBounds(const std::string& msg);

void container::remove(int index) {

    if (index < 0 || index >= size()) {
        throw new IndexOutOfBounds("Invalid index: " + index);

    // the rest of method

Do you see the mistake? Programmer assumed that expression "Invalid index: " + index evaluates to std::string("Invalid index: <some number>").

In fact type of expression "Invalid index: " is char[15], so char[15] + integer results in --- more or less --- char*. For index in range [0, 15] exception will carry tail of the message; for example when index=10 then it will be "dex: ". But for indexes larger than 15 and less than 0 program likely crash.

This is why I hate C++, the language has many dark corners, stupid conventions, implicit conversion, not to mention UB ("just" 150 UB, if you're curious).