Uninitialised Memory (CWE-457, CWE-908)
In C, a local variable without an initialiser, a block from malloc, and the padding inside a struct all start with whatever bytes were there before: the remains of an earlier function's frame, a freed object, another user's request. Reading them is undefined behaviour for variables, and in every case it means the program's decision or output depends on old data. That has two security faces. Decisions: an uninitialised level or ok flag can grant access on one run and refuse it on the next. Leaks: a struct copied to the network or to user space carries old stack or heap bytes in its padding and unused fields; Linux kernel information leaks of exactly this kind were reported for years, and they are a standard way to obtain pointers that defeat ASLR.
Definitions
- Uninitialised read: using a value before anything wrote it. AddressSanitizer does not detect it: the memory is validly allocated.
- MemorySanitizer (MSan): Clang only (
-fsanitize=memory). It tracks, for every bit of memory, whether it has been initialised ("shadow" bits) and reports when an uninitialised value decides a branch, is used as a pointer or index, or is passed to a system call. With-fsanitize-memory-track-originsit also says where the value came from. - Valgrind Memcheck detects the same class without recompiling ("Conditional jump or move depends on uninitialised value(s)"), much more slowly.
-ftrivial-auto-var-init=zero|pattern(GCC 12+, Clang): the compiler initialises every automatic variable that the code didn't, with zeros or a recognisable pattern. A mitigation, not a fix.
The bug in a toy program
access_level maps a user id to a level, but only handles ids 1 and 2. For any other id, level is returned without ever being written, and the caller compares it with 3 to decide on admin access. The session compiles it with both compilers' warnings and then with MSan:
cat > uninit.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
/* Returns the access level for a user id; -1 for unknown users. */
static int access_level(int id) {
int level;
if (id == 1) level = 3; /* admin */
else if (id == 2) level = 1; /* user */
/* BUG: no else branch, level stays uninitialised for other ids */
return level;
}
int main(int argc, char **argv) {
int id = argc > 1 ? atoi(argv[1]) : 1;
if (access_level(id) >= 3)
printf("id %d: admin access\n", id);
else
printf("id %d: limited access\n", id);
return 0;
}
SRC
echo "== gcc -Wall -O2"
gcc -Wall -O2 uninit.c -o u-gcc 2>&1 | grep -E 'warning|note'
echo "== clang -Wall"
clang -Wall -O0 uninit.c -o u-clang 2>&1 | grep -E 'warning'
echo "== MemorySanitizer"
clang -g -O0 -fsanitize=memory -fsanitize-memory-track-origins uninit.c -o u-msan
msan() { # MSan needs a layout ASLR sometimes refuses in this container: retry until it starts
for try in $(seq 40); do out=$("$@" 2>&1); rc=$?; grep -q 'CHECK failed' <<<"$out" || break; done
printf '%s\n' "$out" | grep -vE '^$|#[2-9] '; echo "exit code: $rc"
}
msan ./u-msan 1
msan ./u-msan 7
echo "== the mitigation: -ftrivial-auto-var-init"
gcc -O0 -ftrivial-auto-var-init=zero uninit.c -o u-zero && ./u-zero 7== gcc -Wall -O2
== clang -Wall
uninit.c:8:14: warning: variable 'level' is used uninitialized whenever 'if' condition is false [-Wsometimes-uninitialized]
uninit.c:6:14: note: initialize the variable 'level' to silence this warning
1 warning generated.
== MemorySanitizer
id 1: admin access
exit code: 0
==31==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x5d08fee1f92c in access_level /home/learner/uninit.c:10:5
#1 0x5d08fee1f624 in main /home/learner/uninit.c:15:9
Uninitialized value was created by an allocation of 'level' in the stack frame
#0 0x5d08fee1f7bf in access_level /home/learner/uninit.c:6:5
SUMMARY: MemorySanitizer: use-of-uninitialized-value /home/learner/uninit.c:10:5 in access_level
Exiting
exit code: 1
== the mitigation: -ftrivial-auto-var-init
id 7: limited access
Three observations:
- GCC 13 printed nothing for this code, even with
-Wall -O2: its-Wmaybe-uninitializeddepends on what the optimiser sees and misses many cases. Clang's-Wsometimes-uninitialized(part of-Wall) caught it at compile time and even named the branch. Compile with both compilers in CI where you can. - MSan reports
use-of-uninitialized-valueatuninit.c:10:5, thereturn level, called frommainat line 15. Clang 16 and later check values when they are passed to and returned from functions (-fsanitize-memory-param-retval, on by default), so the report points at the return rather than at the comparison inmain. The origin line,Uninitialized value was created by an allocation of 'level' in the stack frame … uninit.c:6, is the declaration. The run with id 1, wherelevelis written, is clean. (Themsanhelper in the session retries the start-up: MSan reserves fixed address ranges, and in this container ASLR sometimes puts the program where MSan can't work, so it tries to restart without randomisation, which the sandbox forbids. On a normal Linux machine it starts first time.) - With
-ftrivial-auto-var-init=zerothe unknown id deterministically gets level 0, limited access. The bug is still there (the function returns a level for a user it doesn't know); the mitigation only makes its effect predictable and safe in this case. Windows (Microsoft's InitAll), Chrome (on every platform except official Android builds) and Android's kernels build with automatic initialisation for this reason, and the Linux kernel offers it asCONFIG_INIT_STACK_ALL_ZERO.
Root cause
A variable with more paths that read it than paths that write it. Here the "unknown id" path was never thought about. The comment even documents the intended behaviour (-1 for unknown users) that the code doesn't implement.
The fix
Initialise at the declaration to the safe value, and make the unknown case explicit:
#include <stdio.h>
/* Returns the access level for a user id; -1 for unknown users. */
static int access_level(int id) {
switch (id) {
case 1: return 3; /* admin */
case 2: return 1; /* user */
default: return -1; /* unknown: no access */
}
}
int main(void) {
int ids[] = {1, 2, 7};
for (int i = 0; i < 3; i++) {
int lvl = access_level(ids[i]);
printf("id %d: level %2d, %s\n", ids[i], lvl, lvl >= 3 ? "admin access" : lvl >= 0 ? "limited access" : "denied");
}
return 0;
}id 1: level 3, admin access
id 2: level 1, limited access
id 7: level -1, denied
For leaks through structs and buffers, the fix is to zero before filling and to copy out only what was written: struct reply r = {0}; or memset(&r, 0, sizeof r) before setting fields (because = {0} is not guaranteed to clear padding in every compiler), calloc instead of malloc for buffers that are sent somewhere, and sending len bytes, not sizeof buf. See How C Objects Map to Bytes for where padding hides.
How uninitialised reads are detected
- Compiler warnings: Clang
-Wuninitialized -Wsometimes-uninitialized, GCC-Wuninitialized -Wmaybe-uninitialized(better at-O2), GCC's-fanalyzer(-Wanalyzer-use-of-uninitialized-value). - MSan in CI with Clang. Its catch: every library in the process must be built with MSan (including the C++ standard library), or it reports false positives for memory those libraries initialised. That is why MSan is usually run on fuzzing targets with fully instrumented dependencies, as OSS-Fuzz does.
- Valgrind Memcheck when recompiling isn't possible.
- KMSAN in the Linux kernel, and syzkaller fuzzing, found many kernel info-leaks of this class.
The CWE
CWE-457: Use of Uninitialized Variable for locals, CWE-908: Use of Uninitialized Resource for memory in general. Leaks of uninitialised memory to an outside party are also CWE-200 (Exposure of Sensitive Information).
Pitfalls
- ASan won't find these. A clean ASan run says nothing about initialisation; you need MSan, Valgrind or the warnings.
mallocmemory looks zeroed in small tests because fresh pages from the kernel are zero. Reused blocks aren't. Tests that pass on a fresh heap prove nothing.- Silencing the warning with a meaningless value (
int level = 0;when 0 means something) can turn a crash-or-leak into a quiet logic bug. Initialise to the value that is safe when the variable is not set.
Practice
1. Why can't AddressSanitizer report the uninitialised level?
ASan checks whether an address may be accessed. level is a valid local in a live frame; reading it is a legal access as far as addressability goes. Only the value is undefined, which is what MSan tracks.
2. A function fills struct stat_reply { uint8_t kind; uint64_t size; } field by field and sends sizeof bytes. What leaks?
The 7 padding bytes between kind and size (offsets 1–7), which hold whatever the stack contained. Zero the struct first, or serialise the two fields into a byte buffer.
3. Is -ftrivial-auto-var-init=zero enough to close the bug in the toy?
It makes this toy deny access deterministically, so the security impact is closed here. It doesn't cover heap memory or padding of malloced structs, and in other code 0 may be the dangerous value (for example "uid 0"). Fix the code; keep the flag as defence in depth.
Test yourself
Which tool detected the uninitialised read at run time?
- AddressSanitizer
- MemorySanitizer (clang -fsanitize=memory)
- LeakSanitizer
- checksec
Which compiler warned at build time in the session?
- gcc -Wall -O2
- clang -Wall (-Wsometimes-uninitialized)
- Both
- Neither
What does -ftrivial-auto-var-init=zero do?
- Fixes the logic
- Initialises automatic variables the code left uninitialised with zero, making the effect predictable
- Zeroes the heap
- Turns on MSan
Why does MSan need every library to be instrumented?
- For speed
- Otherwise it doesn't see the initialisation done inside uninstrumented code and reports false positives
- It doesn't
- For ASLR