Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider $version (sch jbop) (X_X)@==(Q_Q)@

...

Reusing variable names leads to programmer confusion about which variable is being modified. Additionally, if variable names are reused, generally one or both of the variable names are too generic.

...

Noncompliant Code Example

This non-compliant 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 programmer unintentionally copies a string to the locally declared msg array within the report_error() function, failing to initialize the assign global variable and resulting in a potential buffer overflow.

Code Block
bgColor#FFCCCC
char msg[100];

void report_error(const char const *error_msg) {
  char msg[80];
  /* ... */
  strncpy(msg, error_msg, sizeof(msg));
  return;
}

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

Compliant Solution

This compliant solution uses different, more descriptive variable names.

Code Block
bgColor#ccccff
char system_msg[100];

void report_error(const char const *error_msg) {
  char default_msg[80];
  /* ... */
  if (error_msg)
    strncpy(system_msg, error_msg, sizeof(system_msg));
  else
    strncpy(system_msg, default_msg, sizeof(system_msg));
  return;
}

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

...

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

Risk Assessment

Reusing a variable name in a subscope can lead to unintentionally referencing an incorrect variable.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL01-A C

low

unlikely

medium

P2

L3

Automated Detection

The LDRA tool suite Version 7.6.0 can detect violations of this recommendation.

...

Compass / ROSE can detect violations of this recommendation.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 5.2.4.1, "Translation limits"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "BRS Leveraging human experience" and "YOW Identifier name reuse"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 5.2

...

      02. Declarations and Initialization (DCL)       DCL02-A. Use visually distinct identifiers Image Added