且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 11:30:58

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

There is a simple change you can make to no longer get the C6386 warning. You should test the value of num before attempting the allocation. The C language standard has an interesting statement about passing a size of 0 to malloc().

7.22.3 内存管理函数

7.22.3 Memory management functions

如果请求的空间大小为零,则行为为实现定义:要么返回空指针以指示一个错误,或者行为就像大小是一些非零值,除了返回的指针不得用于访问对象.

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 标准说了类似的话:

The POSIX standard says something similar:

如果大小为 0,则:

应返回空指针,并且可以将 errno 设置为实现定义的值,或

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

应返回指向已分配空间的指针.应用程序应确保指针不用于访问对象.

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

Microsoft's Code Analysis doesn't emit a C6386 for this code:

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;
    }
}