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

问题描述

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

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

警告 C6200 索引“1”超出有效索引范围“0”到“0” 非堆栈缓冲区 '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; 行移到 after 来解决您已检查 ptr 返回的初始 malloc 值是不是NULL

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

您可以使用一些“技巧”来消除这种虚假警告,如下面的代码所示:

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

或者,您可以在 #pragma warning(suppress:6200) 之前添加 ptr[1] = 20; 行 - 这将“暂时”禁用该警告,并且用于下一行,{{3} }:

suppress 将编译指示的当前状态推送到 堆栈,禁用下一行的指定警告,然后弹出 警告堆栈,以便重置编译指示状态。