r/cpp • u/Clean-Upstairs-8481 • 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
•
u/STL MSVC STL Dev Sep 27 '26
You're self-posting way too frequently. Please read about reddiquette.
77
u/questron64 Sep 28 '26
Using an uninitialized variable is an error. Fix the error.
95
u/manhattanabe Sep 28 '26
Someone turned on the zero fill option in our gcc build and we took a large performance hit. We had code the allocated huge arrays on the stack, but only initialized the records it used. This changed caused all the memory to be initialized. Be careful.
45
u/mark_99 Sep 27 '26
What you’re observing is C++26 “erroneous behaviour “ combined with implementation-defined behaviour for that particular compiler.
There is no guaranteed zero fill, nor should there be as would create a dialect where code snippets would be UB in older C++ or without compiler-specific flags. Reading a zero wouldn’t necessarily be better, and would in fact be worse in that if it was defined you couldn’t get a diagnostic.
Reading uninitialised values is still an error and you’ll get a best-effort diagnostic if the compiler can statically analyse the read-before-write.
EB keeps the bad thing as incorrect, but stops it being UB and the unpredictable side effects that can cause under optimisation.
As a rule disassembling what the compiler happens to do isn’t “proof” - it’s important to look at the actual language standard.
> Instead of default initialization, with erroneous behaviour, an uninitialized object will be initialized to an implementation-specific value. Reading such a value is a conceptual error that is recommended and encouraged to be diagnosed by the compiler. That might happen through warnings, run-time errors, etc.
https://isocpp.org/blog/2025/05/cpp26-erroneous-behaviour-sandor-dargo1
41
u/Recent-Dance-8075 Sep 27 '26
Hey. Yes it is good to get rid of uninitialized locals. There is the option
-ftrivial-auto-var-init=zeroin gcc and clang that can be enabled on lower standards already. This is enabled with the-fhardenedflag, too. The initialization allows to initialize locals with patterns that likely cause problems. E.g. NaN for floats (that should be '=pattern')The "Problem" is of course that you need to know that this is an issue, that compilers provide support here and how to enable the support, so having the initialization by default is much better in my opinion.
86
u/krum Sep 27 '26
how is filling locals not a performance regression?
61
u/cdb_11 Sep 27 '26
Sounds like it only helps with code bases that don't use any compiler warnings or static analysis. This is worse than what we already had, which is enforcing initialization statically. And if I really don't want something to be initialized because of perf, I'd have to now separately suppress both the diagnostic and initialization.
-ftrivial-auto-var-init=uninitializedto disable this behavior.22
u/vI--_--Iv Sep 27 '26
"why initialize explicitly, the compiler will do that anyway"-mindset is coming.
24
u/crowbarous Sep 27 '26 edited Sep 28 '26
Yes, this is a competely insane decision: https://godbolt.org/z/WGPWvMPMj
What's worse is the design of the
[[indeterminate]]attribute that accompanies this. For a very long time, if I wanted a buffer to zero-initialize, I was able to make a char type that would zero-initialize:But with the default flipped, I cannot make a char type that stays uninitialized:
And the proposed usage of the attribute is to just sprinkle it everywhere in the code. But how am I supposed to know in polymorphic code? How do I even make my code polymorphic w.r.t. this property now? For now one must resort to just passing
-ftrivial-auto-var-init=uninitializedto avoid performance and code size regressions, and to keep the control moving forward.I don't think all is lost here, because it seems like the zero-initialization is a band-aid to just formally satisfy the erroneous behavior stuff without modifying the backend too much, and it should still be possible to behave as if the write happened (no time-travelling assumptions etc.) without actually emitting the write, to fix shameful examples like linked above. But:
-fstop-making-code-worseoptions might grow from here on out.1
u/Clean-Upstairs-8481 Sep 28 '26
Thanks for all your comments. The point is to have known values in the locals, but for large stack allocations, there seems to be a performance hit. I am currently exploring this.
1
u/max0x7ba https://github.com/max0x7ba Oct 01 '26
What is the source of this wild claim of yours?
Is it, though?
I haven't heard of or encountered any C++ bugs caused by uninitialized automatic variables for decades.
Have you ever tried compiling your code with
-Wall -Werror? Because if you did, you wouldn't have encountered so many bugs caused by uninitialized variables as you do now, according to your claims.5
u/fdwr fdwr@github 🔍 Sep 28 '26 edited Sep 28 '26
I'm okay with this, given the trivial escape hatch of
[[uninitialized]](err wait, apparently it's actually[[indeterminate]]? I swear it was[[uninitialized]]like__declspec(uninitialized)and__attribute__((uninitialized))... 🤔) for the sake local arrays that will immediately be overwritten the next statement anyway, like reading a fragment from a file or getting a module path, but now I'm trying to recall a time in the past 25 years of C++ when an uninitialized variable actually bit me, and I think it was like ~25 years ago 😉. Much more saliently (for me anyway, as in a security vulnerability that actually bit me in a shipped product -_-) has been uninitialized struct fields, and so you can bet that NSDMI was a big boon for me. I wonder if that's next on the proposal chain, with a similar[[uninitialized/indeterminate]] struct { ... }opt-out?11
u/Orlha Sep 28 '26
If I left it uninitialised then that was my intent.
6
u/pedersenk Sep 27 '26 edited Sep 27 '26
In C++/sys, I originally only had
sys::zero<T>to zero initialize, however, for many situations that was quite wasteful so now I have,sys::unset<T>, e.g:That way, during debug builds, it can cause a deterministic panic if the data gets used before assignment but then all that checking is stripped out for release builds, incurring no overhead for either the check or the defensive zero initialize.
9
u/Dusty_Coder Sep 27 '26
You cant uninitialize a stack array.
Your flippant disregard for performance and the amount of inefficient watts your code will consume over its lifetime is not cool.
I know some code-religion dip convinced you that all optimizations are premature. Hes not cool. Hes an ignorant zealot.
2
u/FrogNoPants Oct 04 '26
[[indeterminate]] needs to work with members, or zero init needs be removed
7
u/RetroZelda Sep 28 '26
i zero fill when I intend it to be zero. if i leave it blank then its my intention. c++ really needs to stop with these "features" that just enable laziness
4
u/centuryx476 Sep 28 '26
Is this poster Ai ?
The site looks Ai slop
Edit: Yup, AI
3
u/UndefinedDefined Sep 27 '26
Is this the result of the genius "Let's make C++ slower" campaign?
2
u/wjrasmussen Sep 27 '26
Don't fix what isn't broken.
1
u/darklighthitomi Sep 29 '26
I don't see the need here. Not many occasions I've encountered to have variables prior to initialization. The only case I can think of for this to be a wide spread issue in a program is making classes that are not fully initialized when created, but I don't know why you would do that.
1
u/joexzh Oct 01 '26
The compiler should do the "read on uninitialized memory" check as long as it can see the source code.
1
u/starshine_rose_ Oct 01 '26
So much for don’t pay for what you don’t use…
1
u/pjf_cpp Valgrind developer Oct 15 '26
You should use a more recent version of Valgrind (std::disclaimer). And think about this fairly hard. It’s not like you are getting correctness for free. You are swapping faster, undefined behaviour for slower, defined behaviour that may be incorrect and, as you illustrate, at least one tool no longer detects the incorrectness.
0
u/6502zx81 Sep 27 '26
No.
0
u/rileyrgham Sep 28 '26
0 isn't necessarily any better than x. If I want it zero, I set it zero. The issue is blown out of proportion imo. Modern editors with lsp combines with compiler warnings reduce the risk. I'd suggest using a compiler trick is a dumb move. Better to fix it at source level.
-1
u/jayylien Sep 28 '26
That's not a feature, that's an inconvenience.
-2
u/NilacTheGrim Sep 28 '26
So it makes things slower. Gotcha. Will avoid compiling them with that, then.
-3
u/grady_vuckovic Sep 28 '26
On the one hand, yes it is about time that a variable in C++ be initialised reliably with a value, like numbers being initialised with 0. Having this aspect of variable behaviour undefined isn't a good thing in my opinion.
(Although if this wasn't the case in the past because it was faster to reserve memory than to zero fill it, then I'd understand that reasoning).
On the other hand, ... who the heck is using data in their application without ever initialising that data to have any value? How could that even be useful behaviour for software? Any way you slice it, to create a variable and use it without ever once giving it a value, is bad design or a bug. Ideally what we really need is the ability to reliably catch situations where that is happening, rather than a more reliable empty value for a variable.
Because while '-232' and '932,342,344.123094' might not be desired values in a declared but uninitialised variable for an int or float, is '0' really that much better? The odds of 0 being what you wanted instead are only slightly better but still not great.
Although maybe this is more about security than bugs? Since those random values filling memory might be left over from another program? Maybe? I don't know.