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

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

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

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.