1795
This might seem innocent enough, but str was not initialized, so it contains random memory. As a
result, str[0] might not contain the null terminator, so the copy might start at an offset other than 0.
The consequences can vary, depending on the underlying memory.
If a null terminator is found before str[8], then some bytes of random garbage will be printed before
the "hello world" string. The memory might contain sensitive information from previous uses, such
as a password (which might occur as a result of CWE-14 or CWE-244). In this example, it might not
be a big deal, but consider what could happen if large amounts of memory are printed out before
the null terminator is found.
If a null terminator isn't found before str[8], then a buffer overflow could occur, since strcat will first
look for the null terminator, then copy 12 bytes starting with that location. Alternately, a buffer overread
might occur (CWE-126) if a null terminator isn't found before the end of the memory segment
is reached, leading to a segmentation fault and crash.
Example 4:
This example will leave test_string in an unknown condition when i is the same value as err_val,
because test_string is not initialized (CWE-456). Depending on where this code segment appears
(e.g. within a function body), test_string might be random if it is stored on the heap or stack. If
the variable is declared in static memory, it might be zero or NULL. Compiler optimization might
contribute to the unpredictability of this address.
Example Language: C (Bad)
char *test_string;
if (i != err_val)
{
test_string = "Hello World!";
}
printf("%s", test_string);
When the printf() is reached, test_string might be an unexpected address, so the printf might print
junk strings (CWE-457).
To fix this code, there are a couple approaches to making sure that test_string has been properly
set once it reaches the printf().
One solution would be to set test_string to an acceptable default before the conditional:
Example Language: C (Good)
char *test_string = "Done at the beginning";
if (i != err_val)
{
test_string = "Hello World!";
}
printf("%s", test_string);
Another solution is to ensure that each branch of the conditional - including the default/else branch
- could ensure that test_string is set:
Example Language: C (Good)
char *test_string;
if (i != err_val)
{
test_string = "Hello World!";
}
else {
test_string = "Done on the other side!";
}
printf("%s", test_string);
CWE Version 4.14
CWE-908: Use of Uninitialized Resource
CWE-908: Use of Uninitialized Resource