簡體   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!");
}

它說:

寫入 'temp' 時緩沖區溢出:可寫大小為 '_last*2' 字節,但可能會寫入 '_last' 字節。

這是什么意思? 我肯定知道_last並不比temp.size()大,因為if這樣我該怎么辦?

它在運行時完美運行,但我討厭有警告,這會使其他用戶或我將來難以理解我的代碼。


編輯: _last是用戶在運行時給出的參數,因此它最終可能具有任何值,但如果他的值超出范圍,則會出現異常(在另一個函數中管理)。

我在標題中提到的向量是last , whis 是myClass的成員。

我知道數組的元素從0_last - 1 ,這就是為什么我在第一次使用它之前遞減_last (你可能知道賦值關聯性是從右到左)。


我希望我回答了你所有的評論;)

問題是 C++ 索引從 0 開始的數組。所以大小為 4 的數組具有有效的索引 0、1、2 和 3。

但是您正在分配一個大小為 _last 的數組:

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

然后寫入temp[_last] 那是超出數組大小的一個。

使用向量解決!

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!");
}

出於某種原因,即使您不知道如何,他們也總是能解決所有問題;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM