Local variable declared without an initializer
ID |
c.correctness.uninitialized_local_declaration |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Uninitialized Data |
Language |
C / C++ |
Description
Reports a local variable declaration with no initializer — static, const, extern, and array declarations are excluded, since arrays are commonly left uninitialized ahead of a memset/loop fill and const/extern locals are declared this way by construction.
Rationale
Reading an uninitialized local before it is assigned is undefined behavior in both C and C++, and even when every path does assign it before use, the compiler and a reviewer both have to prove that by tracing every branch — a single missed path (an early return, an added condition later) turns it into a real bug. Deferred initialization is a common and often deliberate C idiom, so this rule is intentionally broad: not every finding is a defect, but each one is a place to double check that every path assigns the variable before it is read.
The following code illustrates the pattern detected by this rule:
struct Point {
int x;
int y;
};
void func(int argc)
{
// FLAGGED: Local variable declared without an initializer
int count;
int total = 0;
static int cache;
const int limit = 3;
extern int shared_counter;
int buffer[16];
// FLAGGED: Local variable declared without an initializer
char *name;
// FLAGGED: Local variable declared without an initializer
struct Point origin;
for (int i = 0; i < argc; i++) {
}
}
Remediation
Give the variable an initial value at the point of declaration whenever one is available. If initialization genuinely has to happen later (e.g., the value depends on a condition evaluated further down), keep the declaration and its first assignment as close together as possible, and make sure every path assigns it before any read.