Buffer Overrun using a Vector

253 Views Asked by At
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.

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?

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).

The vector that I mentioned in the title is last, whis is a member of 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).


I hope I answered all your comments ;)

2

There are 2 best solutions below

3
Simo Pelle On BEST ANSWER

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

2
Goswin von Brederlow On

The problem is that C++ indexes arrays starting with 0. So an array of size 4 has valid indexes 0, 1,2 and 3.

But you are allocating an array of size _last:

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

and then writing to temp[_last]. That is one beyond the size of the array.