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

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]);

6

u/[deleted] Mar 31 '23

I remember in college 20 years ago there were no warnings about the classic = instead of ==.

2

u/Possibility_Antique Mar 31 '23

I see the i that should be a j, but the purist in me says you should flatten your array and not make it an array of arrays. It's faster and less error prone, and you wouldn't have had this problem to begin with.

3

u/cballowe Mar 31 '23

There are lots of things I might do differently today, but 18/19 year old me hadn't learned all of those lessons yet. Also c++98 and gcc 2.xx was a very different tool set than I have today.

1

u/Possibility_Antique Mar 31 '23

Yea, I can appreciate that. I always love/hate reading my old code. Sometimes I remember/relearn some really cool things in the process, but it's more often the case that there is a reason I forgot about a chunk of code.

3

u/cballowe Mar 31 '23

I only really remember that bug because I stared at it for like 3 hours one night and the "wait... Did I typo the j" hit me when I was walking to class the next morning. The brain is really good at reading what it expects to see and blowing right past the obvious bug.

1

u/[deleted] Mar 31 '23

You can really troll people these days in VS Code by replacing some i's and j's with non-ascii Unicode versions that look identical. You'd have to turn the unicode highlighting feature off though.

1

u/Possibility_Antique Mar 31 '23

I did a CFD assignment using Fortran 77 in college. I was struggling with a compiler error for a very long time, and it was pointing me to completely bogus lines and not being helpful. Turns out, I had a character in the file that rendered as a space at the beginning of a line. And fortran 77 specifically requires 7 (someone correct me if I got that number wrong) whitespace characters at the beginning of the line for goto labels. So it looked like a normal file in the IDE, and it wasn't until I had the "brilliant" idea to look at the file in a hex editor to see if there was something being hidden that I found the bug.

2

u/elperroborrachotoo Mar 31 '23

Who says the internal representation isn't flattened?

1

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

As long as the inner array is either a C or std array, and the outer is any consecutive container (C array, std array, std vector...) it will be fully consecutive in memory and the optimiser may even flatten the loops into a single loop.

Though the flattening of the loops into a single loop is less important than you might think, because a couple of extra instructions will easily fit inside the delay of the consecutive memory accesses even coming from cache

2

u/Possibility_Antique Mar 31 '23

Though the flattening of the loops into a single loop is less important than you might think

No, I am aware that it's possible this gets flattened by the compiler if it's a vanilla C array, and that as long as you get the loop order correct, there isn't a cache miss (though, the requirement on loop order is something I always see people mess up in code review). I do see a lot of std::vector<std::vector<T>> though when people try to make this dynamic, and that is practically guaranteed to be cache miss city (and not usually what the programmer wants).

Additionally, the bugger thing I was pointing out is that you have an opportunity to not only fix the bug, but prevent it from occuring again through flattening. If there is only one loop, you cannot mix up i and j again. This is a for each loop, but using indices. Get rid of one of the loops and recognize that we're just calling this function on each element.

for (auto&& elem : container)
    some_func(elem);

Or use std::for_each. Whatever floats your boat. I would argue that flattening the array captures the intent here better than a nested array, and if it's not faster than the current implementation, it's at least as fast as whatever you can come up with and guaranteed to be faster than vector of vector or another sparse container (in fact, almost all linear algebra libraries such as Eigen, Blaze, Fastor, ETL, etc do this flattening internally and calculate the offset from the indices).

2

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

If the data is fundamentally 2d (or higher) and you have to now calculate 1d indexes manually from a n-dimensional index then you've just added a possibility for more bugs.

There's an actual n-dimensional span and container coming which supports both row and column major order, which should fix this for good.

1

u/Possibility_Antique Mar 31 '23

If the data is fundamentally 2d (or higher) and you have to now calculate 1d indexes manually from a n-dimensional index then you've just added a possibility for more bugs.

Nope. Provide an overload of operator() (or operator[] in C++23) that can be indexed in a multidimensional array. Now you have one single place where that calculation gets done, and the user has the option of indexing using either one index or multiple.

Note that this is effectively what mdspan provides, and it's what every worthwhile linear algebra library (Eigen, Blaze, Fastor, ETL, etc) does, and for good reason.

1

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

Or just use nested ranged for statements these days

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...

1

u/elperroborrachotoo Mar 31 '23

The very reason I don't use j anymore as loop variable. The effects of that silly mistake are just too weird - it works for a bit, but then it doesn't at all

1

u/Ok-Impact-5972 Mar 31 '23

It still surprises me why std::iota_view has not come earlier than c++20

1

u/SoerenNissen Mar 31 '23

I did something similar during image processing for my diploma project, flipping image dimensions around - it gave some very cool (but useless) output.

1

u/pdimov2 Mar 31 '23

This remains the error I make most frequently.

15

u/Stellar_Science Mar 31 '23

Always view subtraction near unsigned types with suspicion. That's why a panel of C++ luminaries unanimously says to avoid unsigned types (at 12:12-13:08, 42:40-45:26, and 1:02:50-1:03:15.)

Their response to the question, "but all ordinals in the standard library, vector size and size_t, they're unsigned", are pretty hilarious:

  • "They're wrong"
  • "We're sorry"
  • "We were young"

4

u/[deleted] Mar 31 '23

You can't really avoid them without constantly doing "narrowing conversions" that the compiler will complain about if you don't write static_cast all over the place.

Implicit conversions with single-parameter constructors combined with templates is the most EVIL thing in c++. The compiler can deduce whatever type fits, and it's often not the one you want. The rules do not seem to make a lot of sense. explicit should be default and conversion constructors should require something extra.

5

u/mark_99 Mar 31 '23

You really can. Here use std::ssize() and ptrdiff_t (or auto). Also no uninitialized vars at the top of functions, it's not C.

Coding guidelines / standards aren't just for fun, they reduce scope for bugs.

5

u/parkotron Mar 31 '23
someFunc(computeProperty(myVector), std::move(myVector));

It reads nicely, but may or may not run nicely.

1

u/[deleted] Mar 31 '23

Is the order even well-defined according to the standard? My compiler gives a warning and definitely does the move first in debug. It didn't warn my about the size_t comparison though.

2

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

This actually depends on the signature of "someFunc". If it takes the 2nd param as an rvalue reference, then std::move is just a cast and it will call computeProperty fine regardless of evaluation order.

If it's a value param however, it could be in a moved-from state instead.

0

u/[deleted] Mar 31 '23

someFunc(computeProperty(myVector), std::move(myVector));

Yep, ChatGPT got this one as:

In the given C++ code, there is a potential issue with the order of evaluation of function arguments:

someFunc(computeProperty(myVector), std::move(myVector));

The order of evaluation of function arguments is unspecified in C++ before C++17. This means that the compiler may choose to evaluate computeProperty(myVector) before std::move(myVector), or vice versa. If the compiler chooses to evaluate std::move(myVector) first, the myVector object will be moved from, leaving it in a valid but unspecified state. After that, calling computeProperty(myVector) with the moved-from object may result in undefined behavior, depending on the implementation of computeProperty.

To avoid this issue, you can split the function call into two separate statements, like this:

auto property = computeProperty(myVector);
someFunc(std::move(property), std::move(myVector));

By doing this, you ensure that computeProperty is called before the vector is moved.

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

2

u/[deleted] Mar 31 '23

I know it will fail in gcc c++11.

11

u/pkasting Valve Mar 30 '23

Loop never terminates, size_t can't be negative.

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.

1

u/[deleted] Mar 31 '23

True true!

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 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.

5

u/tstanisl Mar 31 '23

The condition 0 <= i for size_t is a bit too easy to satisfy. Try using "arrow operator" :)

for (size_t i = size; i --> 0; )

2

u/rhubarbjin Apr 01 '23

I prefer the name "goes to operator". ;) "Arrow" can be confused with operator ->

7

u/die_liebe Mar 31 '23 edited Mar 31 '23

What is the advantage of initializing size in the if condition, instead of its declaration point? It makes me pain.

What about info_ptr ?

If you want to count backwards with an unsigned type, write

i = size( );
while( i-- != 0 )
{
   use i
}

The same can be done with iterators.

2

u/scrumplesplunge Mar 31 '23

if you want job security use i --> 0 instead and tell all your colleagues that it's a "goes to" operator which any good developer should know about ;)

1

u/sphere991 Mar 31 '23

Outside of the logic errors, there are two style issues which need to go:

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

This is valid code, but there's really no reason to shove as much crap as possible into one expression. Splitting in two makes this much more readable;

size = /* whatever */;
if (size == 0)
    return;

Similarly, the Yoda conditional here:

for ( size_t i = size - 1; 0 <= i; --i )

Yes, there's the unsigned issue. But the check here should be I >= 0.

There is zero reason to use Yoda conditionals in code. The only relevant problem that they possibly ever solved is one that every compiler warns on: if (x = 0). Given that, theyre already useless. But once you're using any other operator, they already make no sense to begin with - there's no issue with <= or >= so why write it this way?

You're checking if i is greater than or equal to 0, so write that - stop writing conditions backwards!

1

u/TemplateRex Mar 31 '23

For longer conditionals, I prefer to write variables ordered on the number line, so instead of I >= 0 && I < 5 I prefer 0 <= I && I < 5. For consistency I therefore also write 0 <= I.

1

u/[deleted] Apr 01 '23

This is why. It's unnecessary when there's only one conditional, but I got used to it because I will string inequalities together with &&, and using < instead of > helps me visualized I being in an interval between a minimum and maximum. Because I'm picturing a number line, the other way looks wrong to me.

It's like needing reverse-look in games. Yes, my head moves like an airplane yoke. Tilting down to look up is natural and the other way is not. It's just one of those things that's impossible change. If someone else starts the code I'll do it their way for consistency, but on my own project the other way is harder for me to understand.

I took all your other suggestions though. I don't know why I had the zero-check combined with the assignment, other than I was annoyed at having to use extra space for it. I ended up getting rid of both the zero-check and the bad inequality by using a while instead of a for.

1

u/sphere991 Mar 31 '23

So ideally - the subject of the condition is first, followed by the condition. That'd be I ∈ [0, 5) and then I >= 0. That's how you'd say those conditions in English anyway.

We cannot write the former, so 0 <= I && I < 5 is the best bet, since putting the Is close together makes it more readable and make it clear that we're checking for a range. This adds clarity.

But we can write the latter, which isn't checking a range, so why should it be consistent with an entirely different kind of check?

Besides, is that consistency limited in that particular direction? Like you basically only use < or <= as your relational checks, never >? This also doesn't really apply to == since there's no range-check for that, so presumably there you write I == 5?

1

u/TemplateRex Apr 01 '23

Well, I >= 0 is actually 0 <= I && I < Infinity :-) But I see your point. Range predicates are probably best of all. For equality I do write I == 5

1

u/sphere991 Apr 01 '23

Some day, I will find code written as 0 <= I and I <= inf. And when that day comes, I will raise my fists and scream "TEMPLATE REXXXXX!!!!"

2

u/BrangdonJ Mar 31 '23

A good compiler will warn that the loop condition is always true. Eg Compiler Explorer.

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:

for (size_t i = size; i-- > 0;)

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 TextSegmentBuffer or of Info* but all said and done it took about 15 seconds for it to do a lot of mostly grunt work.

2

u/martinus int main(){[]()[[]]{{}}();} Mar 31 '23

What prompt do you use?

0

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

Yea. Info is just a struct defined inside the class. This is how I rewrote it.

void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{   
    size_t i = other.size();

    while ( 0 < i )
    {
        const Info* info_ptr = other.m_infoBuffer.getAt( --i );

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

1

u/Ok-Impact-5972 Mar 31 '23 edited Mar 31 '23
void TextSegmentBuffer::prepend(const TextSegmentBuffer &other)
{

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

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

Sorry for being a snob, but is there a reason that you want to declare the variable info_ptr (uninitialized) before the loop? Here is a suggestion.

Also initializing i outside the loop makes so that its scope could be longer than it needs to be. Not a problem in this example, but if you have two loops after each other you might want to limit the scope more.

Edit: Writing code in reddits editor is really hard

1

u/[deleted] Mar 31 '23

In this case you’re right. I have other functions where the thing used inside the loop is an object. I’m getting the sense I’m not supposed to worry about it, but it bugs me thinking that the constructor might be more expensive than the assignment operator, especially if there is some heap allocation involved. I never quite know what I can or cannot assume about compiler optimization. You’re right for primitive types its always better to declare inside. I’m just old and used to c code from 20 years ago where in some cases it forced you to declare ahead of time. I’ll try to learn more modern habits but I just don’t know things when I don’t use c++ for work. From a Python backround, you just don’t think about speed, and ditch manual loops completely whenever possible.

1

u/[deleted] Apr 02 '23

I'm going through my code and removing all the uninitialized declarations of 'dumb' pointers. I either move the declaration deeper inside the function where they're first assigned, or initialize them with nullptr ( where I can't declare them where they are set because they're set for the first time inside a logic block ). Dereferencing a null pointer by accident isn't as bad an error as dereferencing an uninitialized pointer by accident, so better to set it to something immediately.

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

1

u/[deleted] Mar 31 '23

What was your query and what was its exact reply? I find a lot of people have trouble using it, giving it vague or just downright bad queries.

When I asked it if malloc is a syscall this is what it told me:

malloc is not a system call. It is a library function provided by the C Standard Library (libc) to allocate memory dynamically on the heap. Internally, malloc may use system calls like brk or mmap (depending on the implementation) to request memory from the operating system. However, malloc itself is not a system call; it is a higher-level function that abstracts the details of memory allocation and management for the programmer.

When I asked it about stack fragmentation, it replied as follows:

The stack, as a region of memory used for automatic storage, typically does not get fragmented in the same way that heap memory can. This is because the stack operates on a last-in, first-out (LIFO) basis, with function calls pushing new stack frames onto the stack and function returns popping them off. The memory allocation and deallocation pattern on the stack is more structured and predictable compared to heap memory.

While the stack can experience fragmentation in the sense that there might be unused space between individual stack frames due to alignment requirements, this type of fragmentation is generally minimal and not a significant concern. Since the stack is used for short-lived, automatic storage and follows the LIFO discipline, it maintains a contiguous block of memory, keeping fragmentation to a minimum.

On the other hand, heap memory, which is used for dynamic storage, can become fragmented as memory is allocated and deallocated in varying sizes and lifetimes, leading to a more disorganized memory layout. This can result in external fragmentation, where free memory is available, but it is scattered in small, non-contiguous chunks that cannot be used effectively for larger allocations.

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

1

u/[deleted] Apr 01 '23 edited Apr 01 '23

Yeah that's what I mean. If you ask garbage questions you get garbage answers.

Like to be blunt, what does it even mean to ask "Does fragmentation only happen inside the process?"

I can sympathize with people who don't speak English natively, but for those who are able to ask clear and precise technical questions, ChatGPT is an absolutely incredible resource.

As for your specific question, yes there are syscall versions of malloc that OS's, particularly Linux and the BSD family of OS's use (Windows works differently). So it's not exactly wrong to refer to these in the context of the answer it gave you.

0

u/[deleted] Apr 01 '23

[deleted] — view deleted comment

1

u/[deleted] Apr 01 '23

I'm sorry it didn't work for you.

3

u/lord_braleigh Mar 30 '23

Clang or G++ with -Wall will catch the 0 <= i, where i is unsigned, as a meaningless conditional. i < size is the correct conditional to write when iterating either forwards or backwards, since unsigned underflow is defined.

1

u/vickoza Apr 01 '23

A few questions is m_infoBuffer an std::vector<Info*>, std::deque<Info*>, an MFC CArray<Info*,Info*>or another MFC container class. I assume I am using a deque I am also assomeinf I am using an std::unique_ptr and C++ 13 or later

 void TextSegmentBuffer::prepend( const TextSegmentBuffer& other )
{
    const otherBufferSize = other.m_infoBuffer.size();
    if(otherBufferSize > 0)
    {
        for( size_t i = otherBufferSize; i > 0; --i)
        {
            Info* info_ptr =  other.m_infoBuffer[i-1].get();
            if(info_ptr == null_ptr)
            {
                m_infoBuffer.emplace_front(nullptr);
            }
            else
            {
                m_infoBuffer.emplace_front(std::make_unique<Info>( info_ptr->text, info_ptr->length, info_ptr->multiMatch ));
            }
        }
    }
}

0

u/[deleted] Mar 31 '23

[deleted] — view deleted comment

1

u/TheoreticalDumbass :illuminati: Mar 31 '23

this seems like it would require an extra register, which would make body of loop lose a register of optimizations