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
View all comments
Show parent comment
2
u/tialaramex Sep 29 '26
I think Barry Revzin did the heavy lifting to make it possible to do the same thing in C++ 26 which Rust's
core::mem::MaybeUninit<T>type does. C++ programmers aren't used to that much ceremony but the idea here is to specify to a compiler that you're dealing with a space in memory where aTwould fit, but this isn't necessarily aTyet, then you're writing data to that memory, and then finally once you're happy you are saying this is aTnow. The compiler can follow along and produce high performance code which doesn't have surprising "optimisations" you didn't want, it doesn't need to zero initialize these bytes, it doesn't need to worry about the lifetime of a thing in this space because we've said maybe there isn't anything here, and then when we're all finished writing data we say OK, now this value exists, its lifetime begins, now it's going to run destructors if it goes out of scope and so on.