...
This noncompliant code example declares the msg
identifier at file scope and reuses the same identifier to declare a character array local to the report_error()
function. The programmer may unintentionally copy the function argument to the locally declared msg
array within the report_error()
function. Depending on the programmer's intention, this it either fails to initialize the global variable msg
or allows the local msg
buffer to overflow by using the global value msgsize
as a bounds for the local buffer.
...
This compliant solution uses different, more descriptive variable names.:
Code Block | ||||
---|---|---|---|---|
| ||||
static char message[100]; static const size_t message_size = sizeof( message); void report_error(const char *str) { char msg[80]; snprintf(msg, sizeof( msg), "Error: %s\n", str); /* ... */ } int main() { /* ... */ report_error("some error"); } |
...
By using different variable names globally and locally, the compiler forces the developer to be more precise and descriptive with variable names.
Exceptions
DCL01-EX1: A function argument in a function declaration may clash with a variable in a containing scope provided that when the function is defined, the argument has a name that clashes with no variables in any containing scopes.
Code Block | ||||
---|---|---|---|---|
| ||||
extern int name; void f(char *name); // declarationDeclaration: no problem here // ... void f(char *arg) { // definitionDefinition: no problem, arg doesn't hide name // use arg } |
...
CERT C++ Secure Coding Standard | DCL01-CPP. Do not reuse variable names in subscopes |
MISRA - C:2012 | Rule 5.23 (required) |
...