Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
char msg[100];
/* ... */
void report_error_message(const char *error_msg) {
  char msg[80];
  /* ... */
  /* Assume error_msg isn't too long */
  strcpy(msg, error_msg);
  return;
}
/* ... */

/* Ensure error_msg isn't too long */
if (strlen( error_msg) >= sizeof( msg)) {
  error_msg[sizeof(msg) - 1] = '\0';
}
report_error_message( error_msg); /* oops! */

...

This compliant solution uses different, more descriptive variable names. Also it uses strcpy_s().

Code Block
bgColor#ccccff
char system_msg[100];
/* ... */
void report_error_message(const char *error_msg) {
  char default_msg[80];
  /* ... */
  /* Assume error_msg isn't too long */
  strcpy(system_msg, error_msg);
  return;
}
/* ... */

/* Ensure error_msg isn't too long */
if (strlen( error_msg) >= sizeof( system_msg)) {
  error_msg[sizeof(msg) - 1] = '\0';
}
report_error_message( error_msg); /* good */

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.

...