简体   繁体   English

使用向量的缓冲区溢出

[英]Buffer Overrun using a Vector

unsigned short* myClass::get_last(size_t _last) const
{
    if (_last == 0) _last = last.size();
    if (_last <= last.size())
    {
        unsigned short* temp = new unsigned short [_last] {};
        while (_last > 0) temp[_last] = last[last.size() - _last--]; //I get a warning HERE
        return temp;
    }
    throw std::runtime_error("Error!");
}

It says:它说:

Buffer overrun while writing to 'temp': the writable size is '_last*2' bytes, but '_last' bytes might be written.写入 'temp' 时缓冲区溢出:可写大小为 '_last*2' 字节,但可能会写入 '_last' 字节。

What does it mean?这是什么意思? I know for sure that _last is not greater that temp.size() because of the if so what should I do?我肯定知道_last并不比temp.size()大,因为if这样我该怎么办?

It perfectly works at runtime, but I hate having warnings which make my code less understandable by other user or by me in the future.它在运行时完美运行,但我讨厌有警告,这会使其他用户或我将来难以理解我的代码。


EDIT: _last is an argument given by the user at runtime, so it could eventually have any value, but if his values are out of the range you get an exception (managed in another function).编辑: _last是用户在运行时给出的参数,因此它最终可能具有任何值,但如果他的值超出范围,则会出现异常(在另一个函数中管理)。

The vector that I mentioned in the title is last , whis is a member of myClass .我在标题中提到的向量是last , whis 是myClass的成员。

I know that the elements of an array go from 0 to _last - 1 , and this is why I decrement _last before using it the first time (as you probably know assignement associativity is right-to-left).我知道数组的元素从0_last - 1 ,这就是为什么我在第一次使用它之前递减_last (你可能知道赋值关联性是从右到左)。


I hope I answered all your comments ;)我希望我回答了你所有的评论;)

The problem is that C++ indexes arrays starting with 0. So an array of size 4 has valid indexes 0, 1,2 and 3.问题是 C++ 索引从 0 开始的数组。所以大小为 4 的数组具有有效的索引 0、1、2 和 3。

But you are allocating an array of size _last:但是您正在分配一个大小为 _last 的数组:

unsigned short* temp = new unsigned short [_last] {};

and then writing to temp[_last] .然后写入temp[_last] That is one beyond the size of the array.那是超出数组大小的一个。

Solved using Vectors!使用向量解决!

std::vector<unsigned short> Tombola::get_last(size_t _last) const
{
    if (_last == 0) _last = last.size();
    if (_last <= last.size())
    {
        std::vector<unsigned short> temp(_last);
        while (_last > 0) temp[_last] = last[last.size() - _last--];
        return temp;
    }
    throw std::runtime_error("Error!");
}

For some reason they always solve all problems even if you don't know how ;)出于某种原因,即使您不知道如何,他们也总是能解决所有问题;)

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

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