- 函数名称: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'字节。
事实是代码可以正常工作,可以编译。
这是一条警告,指出缓冲区可能已溢出,并试图警告您在生产代码中添加更多检查。 不一定是错误。