有损指针转换¶
ID: cpp/lossy-pointer-cast
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- correctness
- types
Query suites:
- cpp-security-and-quality.qls
此规则查找将指针类型表达式(隐式或显式)转换为较小大小的整数类型的表达式。这会导致较大整数类型最高有效位被截断。
此类转换高度不可移植,因为整数和指针类型的相对大小可能因架构而异。例如,在 32 位架构中,`int` 类型和 `char*` 类型都是 4 字节宽,但在 64 位机器上,后者占用 8 字节。
建议¶
避免在指针类型和整数类型之间进行转换。
示例¶
void f(char *p) {
int my_ptr = p; //Wrong: pointer assigned to int, would be incorrect if sizeof(char*)
//is larger than sizeof(int)
//...
}