Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: light editing

...

This defect results from a failure to consider all possible data states. (See MSC01-C. Strive for logical completeness.) Once the problem is identified, it can be trivially repaired by accounting for the possibility that number can be equal to 0.

Note also that unless doing so is prohibitive for performance reasons, an additional defense-in-depth practice worth considering is to initialize local variables immediately after declaration. Although compilers and static analysis tools often detect uses of uninitialized variables when they have access to the source code, diagnosing the problem is difficult or impossible when either the initialization or the use takes place in object code for which the source code of which is inaccessible to the tool. Unless doing so is prohibitive for performance reasons, an additional defense-in-depth practice worth considering is to initialize local variables immediately after declaration.

Code Block
bgColor#ccccff
langc
#include <assert.h>
 
void set_flag(int number, int *sign_flag) {
  if (sign_flag == NULL)
    return;

  if (number >= 0) { /* account for number being 0 */
    *sign_flag = 1;
  }
  else {
    assert(number < 0);
    *sign_flag = -1;
  }
}

int is_negative(int number) {
  int sign = 0;   /* initialize as a matter of defense-in-depth */

  set_flag(number, &sign);

  return sign < 0;
}

...

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 2006]. Because error_log has not been initialized, on architectures making use of a program stack, it  it assumes the value already on the stack at this location (on architectures using a program stack), 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, a buffer overflow occurs.

...

This solution is still problematic because a buffer overflow will occur if the null-terminated byte string referenced by msg is greater than 17 bytes, including the NULL null terminator. The solution also makes use of a " magic number, " which should be avoided. (See DCL06-C. Use meaningful symbolic constants to represent literal values.)

...