简体   繁体   English

缓冲区溢出-似乎无法找到问题

[英]Buffer Overrun - Can't seem to locate the porblem

I'm trying to locate the problem in this simple example code that produces the "Buffer Overrun Warning", and after looking at it for a while I decided to post this in hope of someone maybe seeing the error in my code? 我试图在产生“缓冲区溢出警告”的简单示例代码中查找问题,并且在查看了一段时间之后,我决定将其发布,以希望有人看到我的代码中的错误?

Message: Warning C6386 Buffer overrun while writing to 'tmpArray': the writable size is 'line.public: unsigned int __thiscall std::basic_string,class std::allocator >::length(void) const ()*12*4' bytes, but '52' bytes might be written. 消息: 警告C6386写入“ tmpArray”时缓冲区溢出:可写大小为“ line.public:unsigned int __thiscall std :: basic_string,class std :: allocator> :: length(void)const()* 12 * 4'字节,但可以写入'52'字节。

Example that produces the warning: 产生警告的示例:

#define STEP 12

void main()
{
    std::string line("Hello!");

    float* tmpArray = new float[line.length() * STEP];

    unsigned int v = 0;

    for (unsigned int i = 0; i < line.length(); i++)
    {
        tmpArray[  v  ]  = 0.0f;
        tmpArray[v + 1]  = 0.0f;
        tmpArray[v + 2]  = 0.0f;
        tmpArray[v + 3]  = 0.0f;
        tmpArray[v + 4]  = 0.0f;
        tmpArray[v + 5]  = 0.0f;
        tmpArray[v + 6]  = 0.0f;
        tmpArray[v + 7]  = 0.0f;
        tmpArray[v + 8]  = 0.0f;
        tmpArray[v + 9]  = 0.0f;
        tmpArray[v + 10] = 0.0f;
        tmpArray[v + 11] = 0.0f;

        v += STEP;
    }

    delete[] tmpArray;
}

I don't see where I'm stepping into memory that doesn't belong to tmpArray, I mean the buffer is allocated precisely based on the same values as the string's length and the step-size. 我看不到要进入不属于tmpArray的内存的位置,我的意思是缓冲区的分配是根据与字符串的长度和步长相同的值精确分配的。

Thanks to aschepler who commented above, the solution to this turned out to be to copy the value returned by .length() into a const unsigned int, and then use that in both places, like so: 感谢aschepler的评论,事实证明,解决方案是将.length()返回的值复制到const unsigned int,然后在两个地方都使用它,如下所示:

const unsigned int lineLength = line.length();

Allocation: 分配:

float* tmpArray = new float[lineLength * STEP];

For loop: 对于循环:

for (unsigned int i = 0; i < lineLength; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM