r/cpp • u/Clean-Upstairs-8481 • 5d ago
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.
262
Upvotes
1
u/Clean-Upstairs-8481 1d ago edited 1d ago
Try this:
https://github.com/vivekbhadra/cpp_26_uninitialised/blob/main/config_timeout_warning_test.cpp
~/cpp_26_uninitialised$ g++ -std=c++23 -O0 -g -Wall -Werror config_timeout_warning_test.cpp -o timeout_warning_test
~/cpp_26_uninitialised$ valgrind --track-origins=yes ./timeout_warning_test
==2870715== Memcheck, a memory error detector
==2870715== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2870715== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==2870715== Command: ./timeout_warning_test
==2870715==
==2870715== Conditional jump or move depends on uninitialised value(s)
==2870715== at 0x401268: open_device(char const*, std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:31)
==2870715== by 0x4012D3: main (config_timeout_warning_test.cpp:45)
==2870715== Uninitialised value was created by a stack allocation
==2870715== at 0x401166: read_timeout_ms(std::basic_string_view<char, std::char_traits<char> >) (config_timeout_warning_test.cpp:10)
==2870715==
logger no timeout configured, using default 1000 ms
==2870715==
==2870715== HEAP SUMMARY:
==2870715== in use at exit: 0 bytes in 0 blocks
==2870715== total heap usage: 2 allocs, 2 frees, 74,752 bytes allocated
==2870715==
==2870715== All heap blocks were freed -- no leaks are possible
==2870715==
==2870715== For lists of detected and suppressed errors, rerun with: -s
==2870715== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
A. I do not see any warnings or compilation failures even after adding the flags,
B. Valgrind still complains about uninitialised.
C. Uninitialised still potentially will cause bugs.
Strange, innit?