...
Non-Compliant Code Example
In this This non-compliant code example , reuses the msg
array has file scope. The programmer sets the value of the msg
array identifier twice: at the start of the program (with file scope) and also local to the report_error()
function. Consequently, the programmer unintentionally copies a string to the locally declared msg
array within the report_error()
function sets, expecting it to be accessed outside the block. Because the reuse of the variable name is reused, however, the outside msg
variable value is not changedfailing to initialize the assign global variable and resulting in a potential buffer overflow.
Code Block | ||
---|---|---|
| ||
char msg[100]; /* ... */ void report_error(const char *error_msg) { char msg[80]; /* ... */ /* Assume error_msg isn't too long */ strcpy(msg, error_msg); return; } int main(void) { /* ... */ /* Ensure error_msg isn't too long */ if (strlen(error_msg) >= sizeof( msg)) { error_msg[sizeof(msg) - 1] = '\0'; } report_error(error_msg); /* oops! */ /* ... */ } |
...
Compliant Solution
This compliant solution uses different, more descriptive variable names.
...