c6386 写入时缓冲区溢出

c6386 buffer overrun while writing

  • Function Name: expandStack
  • Input: a pointer to a Stack type (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;

}

这一行:expandedStack[i].c = stack->content[i].c; 我收到一条 "green warning" 消息:“c6386 缓冲区在写入 'expandedStack' 时溢出:可写大小为‘2 * (stack->size) * sizeof(Element)’ 字节,但‘2’ 字节可能被写入。

关键是代码运行良好,可以编译。

这是一条警告,表示缓冲区可能已满运行,并试图警告您在生产代码中添加更多检查。 这不一定是错误。 如果你超过运行 缓冲区,你会在 运行 时间内出现异常,即 Stack corruption around local variable ...

调试程序,看看是否出现类似的异常。如果不是,那么您没有超出缓冲区的范围。

我已经检查了错误的详细信息, 'size' 理论上可以为 0,但默认值为 1,永远不会为 0。

我刚刚添加了一个大小不为 0 的检查,它消失了。

谢谢!