c++ - VS2010代码分析奇怪的数组限制报错

标签 c++ arrays visual-studio-2010 code-analysis

我有一个这样定义的类:

#include <cassert>

class Vector
{
     double v[2];

     double operator()(int i) const
     {
         assert(i>=0 && i<2);
         return this->v[i];
     }
};

运行VS2010代码分析工具时,数组访问报错:

warning C6385: Invalid data: accessing 'this->v', the readable size is '16' bytes, but '-16' bytes might be read

但它对我来说似乎完全有效,因为断言应该防止任何负值。发生了什么事?


编辑:代码分析似乎没有正确处理断言:

assert(i<2)

产生

warning C6385: Invalid data: accessing 'this->v', the readable size is '16' bytes, but '24' bytes might be read

同时

assert(i>=0)

产生

warning C6385: Invalid data: accessing 'this->v', the readable size is '16' bytes, but '-16' bytes might be read

用 ifs 替换断言可以解决问题。

最佳答案

这是一个相当古老的问题,但我想在上面发布我的发现:

用 size_t 替换 int 可以修复它,因为 int 可以 < 0,因此您理所当然地得到分析错误。

要修复它,请将其更改为 size_t 或 unsigned int。

静态分析不考虑断言,这就是 if 有效但断言无效的原因。如果你想取消警告,你可以添加:

_analysis_assume(i>0 && i < MY_MAX_VALUE)

这将告诉分析器 i 需要哪些值。

关于c++ - VS2010代码分析奇怪的数组限制报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216985/

相关文章:

c++ - C Char 数组创建差异

c++ - `pragma pack(push, 1)` 在 GCC 4.4.7 中崩溃。可能的编译器错误?

java - 将矩阵存储在数组中

PHP:按日期范围过滤数组

c# - 如何解决 ValidationRule 类属性中的转换问题?

c++ - 如何将参数传递给 Visual Studio 的自定义构建工具?

C++ 验证模板类型

c++ - 在 cpp 中使用 pthread_mutex_t

c++ - 将 float 转换为长指针并返回到 float 指针

c++ - 如何在 Windows 上使用 g2o 框架进行图形优化 (SLAM)?