Versions Compared

Key

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

...

This specific non-compliant code example is from the Linux Kernel Mailing List archive site at http://lkml.org/, although similar examples are common.

...

The sprintf_m() API separates out the return status of the function from information about the number of characters written. In this case, *count is set to the number of characters written in buf while the return value indicates the return status. Returning the status as the return value of the function increases the likelihood that a programmer will check the return status of the function.

One can thus amend the The previous code example thuscan be amended as follows:

Code Block
bgColor#ccccff
int i;
rsize_t count = 0;
errno_t err;

for (i = 0; i < 9; ++i) {
  if ((err = sprintf_m(buf + count, "%02x ", &count,
                        ((u8 *)&slreg_num)[i])) != 0) {
    /* handle print error */
  }
}
if ((err = sprintf_m(buf + count, "%02x ", &count,
                      ((u8 *)&slreg_num)[i]) ) != 0) {
  /* handle print error */
}

...

ERR02-EX1: Null pointers are another example of an in-band error indicator. Use of the null pointers is not quite as bad because it is supported for by the language. According to C99 Section 6.3.2.3, "Pointers":

...

Code Block
bgColor#CCCCFF
/* 
 * The abort_handler_s() function writes a message on the 
 * standard error stream then calls the abort() function.
 */
set_constraint_handler(abort_handler_s);

/*...*/

/* Returns zero on success */
errno_t function(char* dst1){
  char src1[100] = "hello";

  strcpy_s(dst1, sizeof(dst1), src1);
  /* Because handle_errors() never returns,
     we only get here if strcpy_s() succeeds. */

  /* ... */
  return 0;
}

...