使用realloc后如何处理Visual Studio的warning C6011?

How to deal with Visual Studio's warning C6011 after using realloc?

我正在遵循 Microsoft 关于如何解决此警告的指南,但它似乎不起作用。

我添加了所有检查,但是,当我将 'expanded' 指针 tmp 复制到 ptr 并尝试使用它时,我收到另一个警告:

Warning C6200 Index '1' is out of valid index range '0' to '0' for non-stack buffer 'ptr'

void main(void)
{
    int* ptr, * tmp;//I start with two pointers
    ptr = (int*)malloc(1 * sizeof(int));
    ptr[0] = 10;
    if (ptr != NULL)//make sure ptr is not null.
    {
        tmp = (int*)realloc(ptr, 5 * sizeof(int));//expand tmp up to 5
        if (tmp != NULL)//make sure it went well.
        {
            ptr = tmp;
            ptr[1] = 20;
/*
Warning C6200   Index '1' is out of valid index range '0' to '0' for non-stack buffer 'ptr'.    
 */
        }
    }
 }

C6011 警告有效,可以通过将 ptr[0] = 10; 行移动到 来解决 您检查了 ptr 返回的初始值 malloc 不是 NULL.

然而,C6200 警告完全错误,如所讨论的,例如 in this blog

有几个 'tricks' 可以用来消除这个虚假警告,如下面的代码所示:

#include <stdlib.h>

int main(void)
{
    int *ptr, *tmp;//I start with two pointers
    ptr = malloc(1 * sizeof(int));
//  ptr[0] = 10; // Move this to AFTER non-NULL check to avoid C6011...
    if (ptr != NULL)//make sure ptr is not null.
    {
        ptr[0] = 10; // ... moved to here!
        tmp = realloc(ptr, 5 * sizeof(int));//expand tmp up to 5
        if (tmp != NULL)//make sure it went well.
        {
            ptr = tmp;
        //  ptr[1] = 20;
            tmp[1] = 20; // This 'trivial' change silences the C6200
        //  (ptr = tmp)[1] = 20; // ... or you can use this in place of the above two lines!
        }
    }
    free(ptr);
    return 0;
}

或者,您可以在 ptr[1] = 20; 之前添加一个 #pragma warning(suppress:6200) 行 - 这将禁用该警告 'temporarily' 并且 下一行,as described here:

suppress    Pushes the current state of the pragma on the stack, disables the specified warning for the next line, and then pops the warning stack so that the pragma state is reset.