写入时c6386缓冲区溢出 [英] c6386 buffer overrun while writing

查看:544
本文介绍了写入时c6386缓冲区溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 函数名称:expandStack
  • 输入:指向堆栈类型(Stack *)的指针
  • 输出:无
  • 函数操作:该函数扩展堆栈

  void expandStack(Stack * stack){//检查堆栈和数组是否已分配if(堆栈== NULL ||堆栈->内容== NULL){返回;}//分配一个新的大小数组(前一个* 2)Element * ExpandedStack =(Element *)malloc(2 *(stack-> size)* sizeof(Element));//案例malloc失败如果(expandedStack == NULL){printf(错误!Malloc在文件'stack.c','expandStack'函数中失败\ n");返回;}//更新尺寸字段stack-> size * = 2;//将值从先前的数组复制到分配的新数组对于(int i = 0; i< = stack-> topIndex; i ++){ExpandedStack [i] .c =堆栈-> content [i] .c;}//释放旧数组免费(堆栈->内容);//指向堆中的新数组堆栈->内容= ExpandedStack;} 

在这一行中:expandedStack [i] .c = stack-> content [i] .c;我收到绿色警告"的字样:写入'expandedStack'时c6386缓冲区溢出:可写大小为'2 *(stack-> size)* sizeof(Element)'字节,但可能会写入'2'字节.

问题在于代码可以正常工作,可以编译.

解决方案

这是一条警告,指出缓冲区可能已溢出,并试图警告您在生产代码中添加更多检查.不一定是错误.如果您确实超载了缓冲区,则在运行时会出现异常,这表示局部变量周围的堆栈损坏...

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

  • 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;

}

In this line: expandedStack[i].c = stack->content[i].c; I get a "green warning" saying: "c6386 buffer overrun while writing to 'expandedStack': The writeable size is '2 * (stack->size) * sizeof(Element)' bytes, but '2' bytes might be written.

The thing is that the code works fine, it compiles.

解决方案

This is a warning that says that the buffer could be overrun and is trying to warn you to add some more checks in your production code. It is not necessarily an error. If you did overrun the buffer, you would have an exception during run time, which would say Stack corruption around local variable ...

Debug the program, and see if any exception like that comes up. If not, then you are not exceeding the buffer's bounds.

这篇关于写入时c6386缓冲区溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆