这是我的代码:
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 beNULL
(Continue this loop)
Invalid write topArr
, (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/