Re: Possible GCC optimization bug

Jonathan Wakely via Gcc-help <[email protected]> Thu, 12 Feb 2026 17:17:47 +0000
Newsgroups gmane.comp.gcc.help
Message-ID <CAH6eHdRTW4pBGH6P9VASnEfwcroOv1RjDPtNzYXHxv1HrHBWVg@mail.gmail.com>
On Thu, 12 Feb 2026 at 17:10, Jonathan Wakely <[email protected]> wrote:

>
>
> On Thu, 12 Feb 2026 at 16:35, Anubis 1101 <[email protected]> wrote:
>
>> That does appear to "fix" it, but it doesn't tell me what was actually
>> wrong.
>>
>
> It tells you exactly what's wrong. You have undefined behaviour due to
> accessing outside an array. That causes the compiler to turn the code into
> garbage, because it has undefined behaviour.
>
>
>> It just corrects the bad addressing and additionally prints out "runtime
>> error: index 10 out of bounds for type 'char [10]'"... which, yea, I
>> know that. That's half of why I'm here.
>>
>
> So stop doing it then.
>
>
>
>
>> If there's something specific I'm doing that's causing it, that's what
>> I'd like to know. As far as I can tell, there's no flaw in my code itself.
>>
>
> You're accessing data[10] when that is past the end of the array. That
> makes the program's behaviour undefined. Anything can happen.
>
> So fix it. Stop accessing past the end of the array.
>
>

Your concatenate function does not null terminate the string, because there
isn't room for a null terminator.

Then your size() function walks off the end of the array looking for a null
terminator that isn't there. That has undefined behaviour.

Then your length() function does the same thing. That has undefined
behaviour.

A simple fix would be to increase the size of the array (but not increase
the capacity) so that you always have room for a null terminator. This is
one of the most basic things anybody doing C or C++ should know: for a
string of N chars you want a buffer of N+1.

Alternatively, break out of the loops in size() and length() when i ==
Capacity, because the size cannot possibly be more than the maximum
capacity. Looking for a null terminator past the end of the array is a bug,
so stop looking.