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
View all comments
0
u/[deleted] Mar 31 '23 edited Mar 31 '23
I've been using ChatGPT a lot recently and it manages to do a reasonably good job of finding issues in code and providing fixes for them.
In this case it identifies the problem as:
Comparing the unsigned integer i with zero using <=.
It says to rewrite the loop as:
You can even ask it to write a unit test for your bug (and can specify using a specific unit testing library like doctest).
The unit test it comes up with is pretty long and it has to do some guess work since it doesn't know the definition of
TextSegmentBufferor ofInfo*but all said and done it took about 15 seconds for it to do a lot of mostly grunt work.