可疑的指向 void 的指针缩放¶
ID: cpp/suspicious-pointer-scaling-void
Kind: problem
Security severity: 8.8
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-468
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
将任意指针强制转换为 void*
,然后访问其内容时,应谨慎操作。结果可能不具有可移植性。
此查询查找指针运算表达式,其中指向 void
(或类似类型)的指针随后被强制转换为另一种类型并解除引用。
建议¶
尽可能使用数组下标运算符而不是指针运算。例如,用
p[k]
替换*(p+k)
。在使用指针运算之前强制转换为正确的类型。例如,如果
p
的类型为void*
,但实际上它指向类型为double[]
的数组,则使用语法(double*)p + k
获取指向数组中第k
个元素的指针。如果必须使用单字节宽度进行指针运算,则优先使用
char *
而不是void *
,因为对void *
进行指针运算是非标准的 GNU 扩展。
示例¶
char example1(int i) {
int intArray[5] = { 1, 2, 3, 4, 5 };
void *voidPointer = (void *)intArray;
// BAD: the pointer arithmetic uses type void*, so the offset
// is not scaled by sizeof(int).
return *(voidPointer + i);
}
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.