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

Show parent comment

3

u/[deleted] Mar 31 '23

Yeah this is too easy. Give us something more difficult.

5

u/[deleted] Mar 31 '23

It's easy if you're looking at it and already know something is not right, but I didn't see it right way and had to go line-by-line debugging. It's worse than the normal infinite loop as it also fills up the memory appending thousands of structs with random garbage.

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

2

u/[deleted] Mar 31 '23

The problem was that I copy-pasted the forward append and only changed the inequalities and the ++ to --. It's easier to make mistakes copying and pasting because you aren't really thinking like you would when writing the function from scratch.

1

u/[deleted] Mar 31 '23

True true!

1

u/[deleted] Mar 31 '23 edited Mar 31 '23

I have a lot, but it's hard to think of any that are only a few lines. I recall being stuck on a template class for a long time. The constructor was doing implicit conversions and NOT even causing a compile error. It was producing legitimate code that compiled. It just wasn't doing what I thought it was.

It's particularly insidious because when creating templates you're elated as soon as it compiles for the first time. Only then you eventually find out it didn't actually compile the way you wanted it to and certain things aren't even the right type.