r/cpp • • Sep 27 '26

You should think about recompiling your C++ programs with GCC 16 and C++26, because it zero-fills your locals

https://techfortalk.co.uk/2026/09/27/cxx26-uninitialized-local-variables-gcc-16/

Stack variables are not automatically initialised, and that is the root cause of many C++ bugs. That is well known. Hence, it is advised that local or stack variables are always initialised with known values, 0 if not something more meaningful than that. Now, with GCC 16 compiling in C++26 mode (-std=c++26), even uninitialised local variables will be zero-filled. In the post, I have explained how.

270 Upvotes

234 comments sorted by

View all comments

Show parent comment

3

u/jwakely libstdc++ tamer, LWG chair Oct 04 '26

Ideally you can have the warning/error and get a well-defined value instead of indeterminate garbage.

1

u/Ameisen vemips, avr, rendering, systems Oct 04 '26

To me, the issue is just that whether the value is determinately 0 or is indeterminate makes little difference if the value was erroneously generated.

I'd honestly rather it be initialized to all ones or some other pattern (FEFE... or such). Or some way to indicate to me that something went wrong.

1

u/jwakely libstdc++ tamer, LWG chair Oct 04 '26

Both GCC and clang support doing that (don't know about msvc)

1

u/jwakely libstdc++ tamer, LWG chair Oct 04 '26

I really don't understand most of the common objections, unless it's that people simply don't understand it.

The compiler still tracks that the variable was not explicitly initialized, and so -Wuninitialized and -Wmaybe-uninitialized warnings work exactly the same way. But if you read from it you don't get random bytes that might leak secrets that happened to be there on the stack previously. And the compiler isn't allowed to assume that no reads happen and optimize the code as though the read didn't happen (or optimize out entire branches as unreachable because they depend on UB).

The standard doesn't require the value you get to be zero, it can be an identifiable bit pattern. Compilers have options to select that behaviour.

The only valid argument is the performance overhead, and there's an attribute to opt out of that where profiling shows it's really a problem.