【问题标题】:How to deal with Visual Studio's warning C6011 after using realloc?使用 realloc 后如何处理 Visual Studio 的警告 C6011?
【发布时间】:2021-07-08 13:51:59
【问题描述】:

我正在遵循 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'.    
 */
        }
    }
 }

【问题讨论】:

  • 您是否加入了stdlib.h
  • @AndrésSanchez 您使用什么编译器和编译器标志?
  • OT:int main(void)
  • @david-ranieri 是的 已正确包含。
  • 诊断信息似乎太笨了,无法识别 realloc。虽然自然ptr[0] = 10; if (ptr != NULL) 没有任何意义。如果你修复了这个错误,会有什么不同吗?

标签: c visual-studio malloc compiler-warnings realloc


【解决方案1】:

C6011 警告有效,可以通过将ptr[0] = 10; 行移至您检查malloc 返回的初始ptr 值不是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;
}

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

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

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多