循环条件下窄类型与宽类型的比较¶
ID: cpp/comparison-with-wider-type
Kind: problem
Security severity: 7.8
Severity: warning
Precision: high
Tags:
- reliability
- security
- external/cwe/cwe-190
- external/cwe/cwe-197
- external/cwe/cwe-835
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
在循环条件中,如果较宽的值足够大(或足够小),将窄类型的值与宽类型的值进行比较可能会导致意外的行为。 这是因为较窄的值可能会溢出。 这会导致无限循环。
建议¶
更改比较值的数据类型,使较窄一侧的值至少与它所比较的值一样宽。
示例¶
在本例中,bytes_received
在 while
循环中与 max_get
进行比较。 但是,bytes_received
是 int16_t
,而 max_get
是 int32_t
。 由于 max_get
大于 INT16_MAX
,因此循环条件始终为 true
,导致循环永不终止。
在“良好”情况下,由于 bytes_received2
是 int32_t
,与 max_get
的类型一样宽,因此避免了这个问题。
void main(int argc, char **argv) {
uint32_t big_num = INT32_MAX;
char buf[big_num];
int16_t bytes_received = 0;
int max_get = INT16_MAX + 1;
// BAD: 'bytes_received' is compared with a value of a wider type.
// 'bytes_received' overflows before reaching 'max_get',
// causing an infinite loop
while (bytes_received < max_get)
bytes_received += get_from_input(buf, bytes_received);
}
uint32_t bytes_received = 0;
// GOOD: 'bytes_received2' has a type at least as wide as 'max_get'
while (bytes_received < max_get) {
bytes_received += get_from_input(buf, bytes_received);
}
}
int getFromInput(char *buf, short pos) {
// write to buf
// ...
return 1;
}