...
| Code Block | ||||
|---|---|---|---|---|
| ||||
int rc = 0;
int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
/* handleHandle error */
}
|
In this example, stringify >> 24 evaluates to 0xFFFFFF80, or 4,294,967,168. When converted to a string, the resulting value "4294967168" is too large to store in buf and is truncated by snprintf().
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
int rc = 0;
unsigned int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
/* handleHandle error */
}
|
Also, consider using the sprintf_s() function, defined in ISO/IEC TR 24731-1, instead of snprintf() to provide some additional checks. (See STR07-C. Use the bounds-checking interfaces for remediation of existing string manipulation code.)
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
| Can detect violations of this rule. In particular, it flags bitwise operations that involved variables not declared with | |||||||
| CC2.INT13 | Fully implemented | |||||||
5.0 |
| Can detect violations of this recommendation with the CERT C Rule Pack | |||||||
| 50 S | Fully implemented | |||||||
| PRQA QA-C |
| 0502 | Fully implemented | ||||||
|
|
|
...
| [Dowd 2006] | Chapter 6, "C Language Issues" |
| [ISO/IEC C99 Rationale 2003] | Section Subclause 6.5.7, "Bitwise Shift Operators" |
...