带有副作用的 Sizeof¶
ID: cpp/sizeof-side-effect
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- reliability
- correctness
- external/jsf
Query suites:
- cpp-security-and-quality.qls
此规则查找带有副作用的参数的 sizeof
表达式。 sizeof
仅使用参数的类型,因此不会对参数进行求值。在 C99 标准中,对具有动态数组的表达式使用 sizeof
可能或可能不会对副作用进行求值,因此最好完全避免使用它。
建议¶
简化 sizeof
参数,以便仅使用所需类型的子表达式。
示例¶
int f(void){
int i = 0;
char arr[20];
int size = sizeof(arr[i++]); //wrong: sizeof expression has side effect
cout << i; //would output 0 instead of 1
}
参考资料¶
AV 规则 166,联合攻击战斗机空中载具 C++ 编码标准。洛克希德·马丁公司,2005 年。
Tutorialspoint - C++ 编程语言:C++ sizeof 运算符