使用 sizeof 进行可疑加法¶
ID: cpp/suspicious-add-sizeof
Kind: problem
Security severity: 8.8
Severity: warning
Precision: high
Tags:
- security
- external/cwe/cwe-468
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
C 和 C++ 中的指针运算会根据数据类型的大小自动进行缩放。例如,如果 p
的类型为 T*
且 sizeof(T) == 4
,则表达式 p+1
会将 p
增加 4 个字节。
此查询查找形式为 p + k*sizeof(T)
的代码。这种代码通常是错误的,因为不需要手动将偏移量缩放 sizeof(T)
。
建议¶
尽可能使用数组下标运算符而不是指针运算。例如,将
*(p+k)
替换为p[k]
。在使用指针运算之前,强制转换为正确的类型。例如,如果
p
的类型为char*
,但它实际上指向一个类型为double[]
的数组,则使用语法(double*)p + k
获取指向数组中第k
个元素的指针。
示例¶
int example1(int i) {
int intArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *intPointer = intArray;
// BAD: the offset is already automatically scaled by sizeof(int),
// so this code will compute the wrong offset.
return *(intPointer + (i * sizeof(int)));
}
int example2(int i) {
int intArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *intPointer = intArray;
// GOOD: the offset is automatically scaled by sizeof(int).
return *(intPointer + i);
}
参考¶
通用弱点枚举:CWE-468.