You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 14 Next »

Do not use the same variable name in two scopes where one scope is contained in another. Examples include:

  • No other variable should share the name of a global variable.
  • A block should not declare a variable the same name as a variable declared in any block that contains it.

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.

Non-Compliant Code Example

In this example, the programmer sets the value of the msg variable, expecting to reuse it outside the block. Due to the reuse of the variable name, however, the outside msg variable value is not changed.

char msg[100];
{
  char msg[80] = "Hello";
  strcpy(msg, "Error");
}

printf("%s\n", msg);

Compliant Solution

This compliant solution uses different, more descriptive variable names.

char error_msg[100];
{
  char hello_msg[80] = "Hello";
  strcpy(error_msg, "Error");
}

printf("%s\n", error_msg);

Exceptions

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.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL01-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Examples of vulnerabilities resulting from the violation of this rule recommendation can be found on the
CERTwebsite.

References

[[ISO/IEC 9899-1999]] Section 5.2.4.1, "Translation limits"
[[MISRA 04]] Rule 5.2

  • No labels