...
The sprintf()
function returns the number of characters written in the array, not counting the terminating 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.
Compliant Solution (sprintf_m()
)
Wiki Markup |
---|
This compliant solution shows the redesigned API for {{sprintf()}} from the CERT managed string library \[[Burch 06|AA. C References#Burch06]\]. |
...
Code Block | ||
---|---|---|
| ||
int i; ssizersize_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 */ } |
Compliant Solution (sprintf_s()
)
Code Block | ||
---|---|---|
| ||
Exceptions
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":
...