[c6386写入时缓冲区溢出

问题描述 投票:0回答:1
  • 函数名称:expandStack
  • 输入:指向堆栈类型的指针(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;我收到一个“绿色警告”,说:“写入'expandedStack'时c6386缓冲区溢出:可写大小为'2 *(stack-> size)* sizeof(Element)'字节,但可能会写入'2'字节。

事实是代码可以正常工作,可以编译。

c dynamic allocation buffer-overrun
1个回答
0
投票

这是一条警告,指出缓冲区可能已溢出,并试图警告您在生产代码中添加更多检查。 不一定是错误。

© www.soinside.com 2019 - 2024. All rights reserved.