Selen
Selen

Reputation: 210

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

My aim is to set vec array to intData array. I read this question and applied it to my code. I resized intData before doing the process. In C# this intData = GetIntArrayFromByteArray(vec); creates no problem but I am confused when it comes to array vectors in C++. I stated where I get the error as a comment. I tried resizing but it didn't work. Can someone help me please?

Code explanation;

This is GetIntArrayFromCharArray() does the conversion

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

Upvotes: 0

Views: 65

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

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

Whoops!

This is actually:

  • "If the number of bytes is not even, put a zero at the end"
  • "Then always put another zero at the end"

The consequence is that you will always have an odd number of elements. This breaks the subsequent loop as you try to read one past the end of the vector.

I don't think you meant to put that push_back there, or perhaps you meant to have it instead of the resize call.


By the way, as Jarod pointed out, resizing intData up-front is a complete waste of time since the next thing you do with it (as far as we can see) is to replace the whole vector.

Upvotes: 2

Related Questions