![](/img/trans.png)
[英]C6386 - Buffer overrun while writing to 'buffer' when using fread() function
[英]c6386 buffer overrun while writing
- 函数名称:expandStack
- 输入:指向 Stack 类型 (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;
}
在这一行中: expandStack[i].c = stack->content[i].c; 我收到一条“绿色警告”,说:“写入 'expandedStack' 时 c6386 缓冲区溢出:可写大小为 '2 * (stack->size) * sizeof(Element)' 字节,但可能会写入 '2' 字节。
事情是代码工作正常,它编译。
这是一个警告,表示缓冲区可能会溢出,并试图警告您在生产代码中添加更多检查。 这不一定是错误。 如果确实溢出了缓冲区,则在运行时会出现异常,即Stack corruption around local variable ...
调试程序,看看是否有类似的异常出现。 如果不是,那么您没有超出缓冲区的界限。
我已经检查了错误的详细信息,理论上“大小”可以是 0,但默认值是 1,它永远不会是 0。
我刚刚添加了一个大小不为 0 的检查,然后它就消失了。
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.