断言失败错误,C++中的矢量下标超出范围问题

Assertion Failure Error, vector subscript out of range problem in C++

本文关键字:下标 问题 范围 错误 失败 C++ 断言      更新时间:2023-10-16

我的目标是vec数组设置为数组intData。我阅读了这个问题并将其应用于我的代码。在执行该过程之前,我调整了 intData 的大小。在 C# 中,这种intData = GetIntArrayFromByteArray(vec);不会产生任何问题,但是当涉及到C++中的数组向量时,我很困惑。我说明了我在哪里得到错误作为评论。我尝试调整大小,但没有用。有人可以帮我吗?

代码解释;

  • buf收到一条消息(它不为空,我从客户端收到消息(

  • 我创建了一个与buf大小相同的矢量数组vec

  • GetIntArrayFromCharArray()将字符矢量数组转换为 int 数组 向量。

    char buf[1550];//message gets here not empty
    vector<uint16_t> intData; //empty int vector
    //char buf ----> vecor<char> vec
    int n = sizeof(buf) / sizeof(buf[0]);
    vector<char> vec(buf, buf + n);
    intData.resize(vec.size());//here I resize
    
    /*
    irrelevant code piece runs here
    */
    
    if (something == 1)// First fragment
    {
    intData = GetIntArrayFromCharArray(vec);//size out of range error here
    }
    

这是GetIntArrayFromCharArray()进行转换

vector<uint16_t> GetIntArrayFromCharArray(vector<char> arr)
{
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);

vector<uint16_t> intArray;
for (int i = 0; i < arr.size(); i += 2)
intArray.push_back((uint16_t)((arr[i] << 8) | arr[i + 1]));
return intArray;
}
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);

哎 呦!

这实际上是:

  • "如果字节数不均匀,则在末尾加一个零">
  • "然后总是在最后再加一个零">

结果是,您将始终拥有奇数个元素。这会在您尝试读取一个经过向量末尾的循环时中断后续循环。

我不认为你的意思是把那个push_back放在那里,或者你的意思是让它而不是resize电话。


顺便说一下,正如 Jarod 指出的那样,预先调整intData大小完全是浪费时间,因为您使用它做的下一件事(据我们所知(是替换整个向量。