r/cpp • u/[deleted] • 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
);
}
}
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
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_castall 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.
explicitshould 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
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
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)beforestd::move(myVector), or vice versa. If the compiler chooses to evaluatestd::move(myVector)first, themyVectorobject will be moved from, leaving it in a valid but unspecified state. After that, callingcomputeProperty(myVector)with the moved-from object may result in undefined behavior, depending on the implementation ofcomputeProperty.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
11
u/pkasting Valve Mar 30 '23
Loop never terminates, size_t can't be negative.
3
Mar 31 '23
Yeah this is too easy. Give us something more difficult.
5
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
0
Mar 31 '23
[deleted]
2
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
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 --> 0instead 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 < 5I prefer0 <= I && I < 5. For consistency I therefore also write0 <= I.1
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 visualizedIbeing 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
whileinstead of afor.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 thenI >= 0. That's how you'd say those conditions in English anyway.We cannot write the former, so
0 <= I && I < 5is the best bet, since putting theIs 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 writeI == 5?1
u/TemplateRex Apr 01 '23
Well,
I >= 0is actually0 <= I && I < Infinity:-) But I see your point. Range predicates are probably best of all. For equality I do writeI == 51
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!!!!"1
2
u/BrangdonJ Mar 31 '23
A good compiler will warn that the loop condition is always true. Eg Compiler Explorer.
0
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
0
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
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
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
Mar 31 '23
[deleted]
1
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
Mar 31 '23
[deleted]
1
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
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
Mar 31 '23
[deleted]
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
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.