简体   繁体   English

c6386 写入时缓冲区溢出

[英]c6386 buffer overrun while writing

  • Function Name: expandStack函数名称:expandStack
  • Input: a pointer to a Stack type (Stack*)输入:指向 Stack 类型 (Stack*) 的指针
  • Output: none输出:无
  • Function Operation: The function expands a stack函数操作:函数扩展一个堆栈
void expandStack(Stack* stack){

    //Check the stack and the array are allocated
    if (stack == NULL ||stack->content == NULL)
    {
        return;
    }

    //Allocating a new sized array (*2 from the previous)
    Element* expandedStack = (Element*)malloc(2 * (stack->size) * sizeof(Element));

    //Case malloc failed
    if (expandedStack == NULL)
    {
        printf("Error! Malloc has failed in file 'stack.c', 'expandStack' function\n");
        return;
    }

    //Updating size field
    stack->size *= 2;

    //Copy values from the previous array to the new array allocated
    for (int i = 0; i <= stack->topIndex; i++)
    {
        expandedStack[i].c = stack->content[i].c;
    }

    //Free old array
    free(stack->content);

    //Point to the new array in the heap
    stack->content = expandedStack;

}

In this line: expandedStack[i].c = stack->content[i].c;在这一行中: expandStack[i].c = stack->content[i].c; I get a "green warning" saying: "c6386 buffer overrun while writing to 'expandedStack': The writeable size is '2 * (stack->size) * sizeof(Element)' bytes, but '2' bytes might be written.我收到一条“绿色警告”,说:“写入 'expandedStack' 时 c6386 缓冲区溢出:可写大小为 '2 * (stack->size) * sizeof(Element)' 字节,但可能会写入 '2' 字节。

The thing is that the code works fine, it compiles.事情是代码工作正常,它编译。

This is a warning that says that the buffer could be overrun and is trying to warn you to add some more checks in your production code.这是一个警告,表示缓冲区可能会溢出,并试图警告您在生产代码中添加更多检查。 It is not necessarily an error.这不一定是错误。 If you did overrun the buffer, you would have an exception during run time, which would say Stack corruption around local variable ...如果确实溢出了缓冲区,则在运行时会出现异常,即Stack corruption around local variable ...

Debug the program, and see if any exception like that comes up.调试程序,看看是否有类似的异常出现。 If not, then you are not exceeding the buffer's bounds.如果不是,那么您没有超出缓冲区的界限。

I've checked the details of the error, 'size' could theoritically be 0 but the default value is 1 and it would never be 0.我已经检查了错误的详细信息,理论上“大小”可以是 0,但默认值是 1,它永远不会是 0。

I just added a check that size isn't 0 and it disappeared.我刚刚添加了一个大小不为 0 的检查,然后它就消失了。

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM