gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:43:33 24 4
gpt4 key购买 nike

这是我的代码:

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 writablesize 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 isimplementation-defined: either a null pointer is returned to indicatean error, or the behavior is as if the size were some nonzero value,except that the returned pointer shall not be used to access anobject.

POSIX 标准说了类似的话:

If size is 0, either:

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

A pointer to the allocated space shall be returned. The applicationshall 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com