Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Simplified the first pair of examples.

...

This noncompliant code example declares the msg identifier at the start of the compilation unit (with file scope ) and reuses the same identifier to declare a character array local to the report_error() function. Consequently, the The programmer unintentionally copies a string may unintentionally copy the function argument to the locally declared msg array within the report_error() function, either failing to initialize the assign global msg variable and resulting in a potential buffer variable, or by mistakenly using msgsize as the size of the local array potentially causing the local buffer to overflow.

Code Block
bgColor#FFCCCC
static char msg[100];
static const size_t msgsize = sizeof msg;

void report_error(const char *error_msgstr) {
  char msg[80];
  /* ... */
  strncpysnprintf(msg, msgsize, error_msg, sizeof(msg));
  return;"Error: %s\n", str);
  /* ... */
}

int main(void) {
  char error_msg[80];
  /* ... */
  report_error("some error_msg");
  /* ... */
}

Compliant Solution

This compliant solution uses different, more descriptive variable names.

Code Block
bgColor#ccccff
static char system_msgmessage[100];
static const size_t message_size = sizeof message;

void report_error(const char *error_msgstr) {
  char default_msg[80];
  /* ... */
  if (error_msg)
    strncpy(system_msg, error_msg, sizeof(system_msg));
  else
    strncpy(system_msg, default_msg, sizeof(system_msg));
  system_msg[ sizeof(system_msg) - 1] = '\0';
  return;
snprintf(msg, sizeof msg, "Error: %s\n", str);
  /* ... */
}

int main(void) {
  char error_msg[80];
  /* ... */
  report_error("some error_msg");
  /* ... */
}

When the block is small, the danger of reusing variable names is mitigated by the visibility of the immediate declaration. Even in this case, however, variable name reuse is not desirable. In general, the larger the declarative region of an identifier the more descriptive and verbose should be the name of the identifier.

By using different variable names globally and locally, the compiler forces the developer to be more precise and descriptive with variable names.

...