Local, automatic variables can assume _unexpected_ values if they are used before they are initialized. \ [[ISO/IEC 14882-2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 8.5, paragraph 9 says: "... if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value". In practice, this value defaults to whichever values are currently stored in stack memory. While uninitialized memory often contains zero, this is not guaranteed. Consequently, uninitialized memory can cause a program to behave in an unpredictable or unplanned manner and may provide an avenue for attack. Wiki Markup
In most cases, compilers warn about uninitialized variables. These warnings should be resolved as recommended by MSC00-CPP. Compile cleanly at high warning levels.
...
Noncompliant Code Example
...
In this noncompliant code example, the programmer mistakenly fails to set the local variable {{error_log
}} to the {{msg
}} argument in the {{report_error()
}} function \[ [mercy 06|AA. Bibliography#mercy 06]\]. Because {{error_log
}} has not been initialized, on architectures making use of a program stack, it assumes the value already on the stack at this location, which is a pointer to the stack memory allocated to the {{password
}} array. The {{sprintf()
}} call copies data in {{password
}} until a null byte is reached. If the length of the string stored in the {{password
}} array is greater than the size of the {{buffer
}} array, then a buffer overflow occurs.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> #include <ctype.h> #include <string.h> int do_auth(void) { char *username; char *password; /* Get username and password from user, return -1 if invalid */ } void report_error(const char *msg) { const char *error_log; char buffer[24]; sprintf(buffer, "Error: %s", error_log); printf("%s\n", buffer); } int main(void) { if (do_auth() == -1) { report_error("Unable to login"); } return 0; } |
...
This rule appears in the C Secure Coding Standard as EXP33-C. Do not reference uninitialized memory.
Bibliography
\[[Flake 06|AA. Bibliography#Flake 06]\]
\[[] Wiki Markup
[ISO/IEC 14882-2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 8.5 Initializers.
\[
[Lockheed Martin 05|AA. Bibliography#Lockheed Martin 05] \] AV Rule 142 All variables shall be initialized before use.
\
[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "LAV Initialization of Variables"
\
[[mercy 06|AA. Bibliography#mercy 06]\]
...
EXP32-CPP. Do not access a volatile object through a non-volatile reference 03. Expressions (EXP) EXP34-CPP. Ensure a null pointer is not dereferenced