Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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. Consequently, unitialized Thismemory 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.

...

In this example, two functions are called consecutively. The first function, func1(...), is passed an integer entered by a user. That integer is stored in variable : i for the duration of the function. The second function, func2(), declares a local integer variable : j. j is not initialized before being checked against a constant value, CONDITION_CHECK. Because j is uninitialized, it assumes whatever value is at that location in the stack, in this case the value of i from func1(). As a result, if the user entered 42, the condition statement if (j == CONDITION_CHECK) succeeds.

...

Non-Compliant Code Example

In this example derived from mercy 06, the programmer mistakely mistakenly fails to set the local variable mesg to the msg argument in the log_error function. When the sprintf() call dereferences the mesg pointer, it actually dereferences the address that was supplied in the username buffer, which in this case is the address of "password". The sprintf() call copies all of the data supplied in "password" until a NULL byte is reached. Because the '"password' " buffer is larger than {{buffer}} , a buffer overflow occurs.

...

This solution is compliant provided that the null-terminated byte string referenced by msg is 17 bytes or less, including the null terminator. A much simpler, less error prone, and better performing solution is shown below:

...