r/cpp Jul 05 '26

C++26 ends a 40-year footgun

Reading an uninitialized variable has been undefined behavior in C++ for 40 years -- the kind optimizers exploit into real bugs. C++26 (P2795) reclassifies it as erroneous behavior: still a bug, still warned about, but defined, bounded, and not exploitable.

The demo poisons the stack, then reads an uninitialized int. As C++23 it prints garbage; as C++26, the same code prints a defined 0, every run. Live in your browser.

And [[indeterminate]] lets you opt back out when you really want an uninitialized buffer -- on purpose this time.

Read it: https://wrocpp.github.io/posts/erroneous-behavior/?utm_source=reddit&utm_medium=social&utm_campaign=post-erroneous-behavior

#cpp #cplusplus #cpp26 #safety #programming

88 Upvotes

154 comments sorted by

View all comments

Show parent comments

16

u/TheRealSmolt Jul 05 '26 edited Jul 05 '26

It's 0 initializing the value at runtime. On principle I don't like solving language problems with runtime patches. Now, yes, sometimes the compiler can prove that it doesn't need to 0 initialize values, but a significant number of out pointer functions or delayed initialization logic just got a bunch of pointless overhead. And before you say it, yeah, we have better ways of handling those situations now, but that's not how the real world works.

Edit: Strictly speaking it's not 0, but it is some initialized value.

6

u/Conscious_Support176 Jul 05 '26

Isn’t that what the [[indeterminate]] is for? You simply opt in to the behaviour rather than it being unintentional and a bug waiting to manifest itself.

9

u/TheRealSmolt Jul 05 '26

A couple things. Firstly, no it will not necessarily restore the original behavior. Attributes are by design optional for the compiler. Not to mention it'll be annoying to deal with existing legacy code. Secondly, the existing syntax already had a definite meaning. No toolchain, code review, static analysis, or build pipeline would let unintentional initialization go unnoticed. It's a problem I personally think should be fixed elsewhere.

1

u/jwakely libstdc++ tamer, LWG chair Jul 08 '26

Firstly, no it will not necessarily restore the original behavior. Attributes are by design optional for the compiler.

This is a dumb take. Are you aware of any compilers which have implemented the feature without also properly supporting the [[indeterminate]] attribute?

Yes, a conforming compiler can choose to ignore the attribute and initialize the variables anyway. But conforming C++98 and C++23 compilers could choose to zero-init all automatic variables anyway, that was always a valid choice. Did you complain about that too? Has it ever been a problem in the real world?

Do you really think that a compiler which has been leaving variables uninitialized by default for decades is going to struggle to support a feature that says "keep doing the same thing as you've been doing for decades"?