☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

未指向同一数组的指针不可相减

14.6 ID_illPtrDiff
目录 › next › previous

不在同一数组中的地址之间没有连续性,未指向同一数组的指针相减往往意味着逻辑错误,也会导致标准未定义的行为。

如果两个指针的值均为同一数组中的元素地址,或该数组末尾元素的下一个地址,则称两个指针指向同一个数组,其差值为相应地址之间的距离,否则其差值不具备正确意义。

示例:

ptrdiff_t d;

int i, j;
d = &j - &i;   // Non-compliant, undefined if overflow

int x[8], y[8];
d = &x[1] - &x[0];   // Compliant, ‘d’ is 1
d = &y[1] - &x[0];   // Non-compliant, undefined if overflow

int* p = &i;
int* q = NULL;
d = p - q;      // Non-compliant

相关

ID_illPtrComparison

依据

ISO/IEC 9899:1999 6.5.6(9)-undefined ISO/IEC 9899:2011 6.5.6(9)-undefined ISO/IEC 14882:2003 5.7(6)-undefined ISO/IEC 14882:2011 5.7(6)-undefined

参考

CWE-469 MISRA C 2004 17.2 MISRA C 2012 18.2 MISRA C++ 2008 5-0-17 SEI CERT ARR36-C
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.