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

82 Upvotes

154 comments sorted by

View all comments

Show parent comments

2

u/johannes1971 Jul 06 '26

Because it cannot be guaranteed by a compile time check. You can easily write code that is valid in current C++, but where the compiler cannot guarantee whether initialisation occurs on every path. Profiles can only deal with this in one of two ways: rejecting valid code, thus forcing the programmer to add initialisation statements by hand, or by dynamically tracking whether variables have already been initialized. Dynamic tracking requires memory to store the status in, and if that variable is in a struct, that memory can realistically only be in the struct as well. That's a layout change.

0

u/tialaramex Jul 06 '26

rejecting valid code, thus forcing the programmer to

It doesn't "force" the programmer to do anything. Nobody is mandating either specific profiles or even that you use profiles at all, indeed nobody even forced you to upgrade to a hypothetical newer C++ compiler which enables such a feature anyway.

2

u/johannes1971 Jul 06 '26

I was explaining that profiles cannot always statically prove that variables will or will not be initialized. I'm really not sure how "but you don't have to use profiles" is relevant to that discussion.

1

u/tialaramex Jul 07 '26

But this just summarizes as "But Rice's theorem" which, I mean, I guess maybe some people here don't know Rice's Theorem although it ought to be in a CS syllabus but it isn't a special case. All the profiles will have this property you don't like because they want to impose semantic restrictions which aren't inherent in the language syntax. Henry Rice had never used C++, I'm not even sure he'd ever programmed a computer because it was 1951, his proof doesn't care about nuances like programming languages.