...
This noncompliant code example is from the Linux Kernel Mailing List archive site, although similar examples are common.:
Code Block | ||||
---|---|---|---|---|
| ||||
int i; ssize_t count = 0; for (i = 0; i < 9; ++i) { count += sprintf( buf + count, "%02x ", ((u8 *)&slreg_num)[i] ); } count += sprintf(buf + count, "\n"); |
...
This compliant solution shows the redesigned API for sprintf()
from the CERT managed string library [Burch 2006].:
Code Block | ||||
---|---|---|---|---|
| ||||
errno_t sprintf_m( string_m buf, const string_m fmt, int *count, ... ); |
...
In this noncompliant code example, the error handler returns normally, but the strcpy_s()
function's return value is not checked.:
Code Block | ||||
---|---|---|---|---|
| ||||
constraint_handler_t handle_errors(void) { constraint_handler_t data; /* Define what to do when error occurs */ return data; } /*...*/ set_constraint_handler(handle_errors); /*...*/ /* Returns zero on success */ errno_t function(char *dst1){ char src1[100] = "hello"; strcpy_s(dst1, sizeof(dst1), src1); /* At this point strcpy_s may have yielded an error and handle_errors() might have returned */ /* ... */ return 0; } |
...
In this compliant solution, the error handler terminates the program, ensuring that strcpy_s()
never returns unless it fully succeeds.:
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; } |
...
[Burch 2006] | |
[ISO/IEC 9899:2011] | Section 6.3.2 "Other Operands" |
...