...
The sprintf()
function returns the number of characters written in the array, not counting the terminating NULL null character. This number is frequently added to an existing counter to keep track of the location of the index into the array. However, the call to sprintf()
can (and will) return -1 on error conditions such as an encoding error. If this happens on the first call (which is likely), the count
variable, already at zero, is decremented. If this index is subsequently used, it will result in an out-of-bounds read or write.
...
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.
...
ERR02-EX1: Null pointers are another example of an in-band error indicator. Use of NULL null pointers is not quite as bad because it is supported by the language. According to C99 Section 6.3.2.3, "Pointers":
If a NULL null pointer constant is converted to a pointer type, the resulting pointer, called a NULL null pointer, is guaranteed to compare unequal to a pointer to any object or function.
...
Here the code is rectified by having the error handler terminate the program, which ensures that strcpy_s()
actually never returns unless it worked perfectly.
Code Block | ||
---|---|---|
| ||
/*
* The abort_handler_s() function writes a message on the
* standard error stream and 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 abort_handler_s() never returns,
we only get here if strcpy_s() succeeds. */
/* ... */
return 0;
}
|
...
The risk of using in-band error indicators is difficult to quantify , and is consequently given as low. However, if the use of in-band error indicators results in programmers failing to check status codes or incorrectly checking status codethem, the consequences can be more severe.
...