- 函数名称: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; 我收到一个“绿色警告”,说:“ c6386写入'expandedStack'时缓冲区溢出:可写大小为'2 *(stack-> size)* sizeof(Element)'字节,但可能会写入'2'字节。
问题在于代码可以正常工作,可以编译。
答案 0 :(得分:0)
这是一条警告,指出缓冲区可能已溢出,并试图警告您在生产代码中添加更多检查。 不一定是错误。如果确实超载了缓冲区,则在运行时会出现异常,提示为Stack corruption around local variable ...
调试程序,查看是否有类似的异常出现。如果没有,那么您就不会超出缓冲区的范围。