c - 当实际上永远不会发生溢出时,Visual Studio 会发出缓冲区溢出警告

标签 c visual-studio visual-studio-2019 buffer-overrun

这是我的代码:

void foo(int num) {
    int *pArr = (int *)malloc(num * sizeof(int));
    // allocate array of 'sale' structs for each region
    for (int i = 0; pArr != NULL && i < num; i++) {
        pArr[i] = 1;
    }
}

int main() {
    int num = 36;
    foo(num);
}

表达式 pArr[i] = 1; 给出了 C6386 警告

Warning C6386 Buffer overrun while writing to 'pArr': the writable size is 'num*sizeof(int)' bytes, but '8' bytes might be written.

这很奇怪,因为 for 循环的迭代次数和头部数组的大小都取决于 num,所以不会出现溢出'这实际上从未发生过。

然后是详细的解释:

i may equal 1
pArr may be NULL (Continue this loop)
Invalid write to pArr, (outside its writable range)

但这当然是 visual studio 的错误,pArr 不能为 NULL,因为这是进入循环的条件。

如何清除此警告?
谢谢大家

最佳答案

您可以进行简单的更改以不再收到 C6386 警告。在尝试分配之前,您应该测试 num 的值。 C 语言标准有一个关于将大小为 0 传递给 malloc() 的有趣声明。

7.22.3 内存管理函数

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned to indicate an error, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

POSIX 标准说了类似的话:

If size is 0, either:

A null pointer shall be returned and errno may be set to an implementation-defined value, or

A pointer to the allocated space shall be returned. The application shall ensure that the pointer is not used to access an object.

Microsoft 的代码分析不会为此代码发出 C6386:

void foo(int num)
{
    if (num == 0) { // avoid passing 0 to malloc()
        return;
    }
    int *pArr = (int *) malloc(num * sizeof(int));
    // allocate array of 'sale' structs for each region
    for (int i = 0; pArr != NULL && i < num; i++) {
        pArr[i] = 1;
    }
}

关于c - 当实际上永远不会发生溢出时,Visual Studio 会发出缓冲区溢出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65550981/

相关文章:

c++ - 如何读取大 json?

C:将数组转换为RGB图像

visual-studio - Visual Studio 查找所有未引用的内容

docker - 在 Visual Studio 2019 中运行 Docker Compose 项目时 FileLoadException 访问被拒绝

c - 曾几何时,> 比 < ... 快,什么?

c - 在C中,有没有办法获取名称与字符串匹配的多个文件的大小?

c++ - Visual Studio 2013 语法突出显示停止工作

C 内联程序集生成未处理的异常

visual-studio-2019 - 关于 Vs2019 社区或专业或企业

visual-studio - Visual Studio 在 Debug模式下运行没有 docker 的支持 Docker 的项目