Wiki Markup |
---|
Local, automatic variables can assume _unexpected_ values if they are used before they are initialized. C99 specifies "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate." \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] In practice, this value defaults to whichever values are currently stored in stack memory. While unitialized memory often contains zero, this is not guaranteed. This can consequently cause a program to behave in an unpredictable or unplanned manner, and may provide an avenue for attack. Some compilers warn about unitialized variables, but these can be ignored by the programmer. As a result, it is necessary to guarantee that all local variables are initialized with a default value. The value assigned should be documented as the _default value_ for that variable in the comments associated with that variable's declaration. |
...
Code Block |
---|
#define CONDITION_CHECK 42 void func1 (int arg) { int i = arg; } void func2 (void) { int j; if (j == CONDITION_CHECK) printfputs("Condition passed!!\n"); else printfputs("ERROR: Condition failed\n"); } int main(int argc, char **argv) { func1(atoi(argv[1])); ... func1(i); /* the value of i originates from an untrusted source */ func2(); }... |
Compliant Solution 1
The local, automatic variable j
should be initialized to a default value.
Code Block |
---|
#define CONDITION_CHECK 42 void func1 (int arg) { int i = arg; } void func2 (void) { int j = 0; /* initialize j to 0 */ if (j == CONDITION_CHECK) printfputs("Condition passed!!\n"); else printfputs("ERROR: Condition failed\n"); } int main(int argc, char **argv) { func1(atoi(argv[1])); ... func1(i); /* the value of i originates from an untrusted source */ func2(); }... |
Non-compliant Code Example 2
In this example, user input is copied to a buffer, the character array buf
. The first function, logit()
function copies the user input to another buffer, buffer
, and prints it to standard output. Next, the runit()
routine is called. This routine declares an array of 50 characters, buf
, and a character pointer, ptr
. However, since ptr
is not initialized it references data used by the last function called, in this case, the contents of the user controlled data copied in the logit()
function. When the data referred to by ptr
is copied to buf
using an unbounded strcpy()
, ptr
is dereferenced and the data in that location is copied to buf
. If the memory referred to by ptr
contains more than 50 characters without a null character, a buffer overflow will occur.
...