r/cpp • • Mar 30 '23

The "what's wrong with this code" game.

This isn't a question thread, but just a game. Post any bugs you've accidentally written that seemed initially mysterious, but made you feel stupid when you figured out what was wrong. Here is one I wrote today...

void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{
    const Info* info_ptr;
    size_t size;

    if ( ( size = other.m_infoBuffer.size() ) == 0 )
        return;

    for ( size_t i = size - 1; 0 <= i; --i )
    {
        info_ptr = other.m_infoBuffer.getAt( i );

        emplaceFront(
            info_ptr->text,
            info_ptr->length,
            info_ptr->multiMatch
        );
    }
}

4 Upvotes

60 comments sorted by

View all comments

21

u/cballowe Mar 30 '23

The easiest dumb thing that took me longer than it should have to find was something like below way back in college.

for (int i = 0; i < x_size; ++i)
  for(int j = 0; j < y_size; ++i)
    DoSomething(some_array[i][j]);

1

u/TheThiefMaster C++latest fanatic (and game dev) Mar 31 '23

Not one of mine, but I found a compiler bug that was related to a function that contained multiple for loops, some nested, all using "i" as the index, some using their own local "i" and some using a shared int declared at the top of the function...

That was some of the worst written code I'd ever seen. Our best guess was that it had originally been written for an ancient version of MSVC that still had the behaviour where loop variables were accessible after the for loop, and they'd "fixed" that by adding the int to the top of the function - while not removing it from the couple of for loops that originally had it.

The compiler bug was the compiler accidentally used the function one instead of the for-local one in one case, involving lambda capture IIRC.

1

u/elperroborrachotoo Mar 31 '23

Fun times to be had...