2

I have a function like the following that takes in a pointer to the start of a c style array, creates a vector and then copies the data from this vector into the c style array.

Using std::copy with .begin() and .end() does not copy it properly but the other 2 methods I have posted below work and I was wondering why.

This does not work:

void copyArr(uint8_t* Arr1)
{
    std::vector<uint8_t> Arr2;
    Arr2.reserve(100);

    for ( int i = 0; i < 100; ++i )
    {
        Arr2[i] = 5;
    }

    std::copy(Arr2.begin(), Arr2.end(), Arr1);
}

But this will work

void copyArr(uint8_t* Arr1)
{
    std::vector<uint8_t> Arr2;
    Arr2.reserve(100);

    for ( int i = 0; i < 100; ++i )
    {
        Arr2[i] = 5;
    }

    // This works.
    std::copy(Arr2.begin(), Arr2.begin() + 100, Arr1);

    // This will also work.
    //std::copy(&Arr2[0], &Arr2[100], Arr1);
}
Burton2000
  • 1,972
  • 13
  • 23
  • 3
    Check `Arr2.size()` or `Arr2.empty()`. This is UB. – nwp Apr 30 '19 at 12:09
  • 5
    Then read ["std::vector::resize() vs. std::vector::reserve()"](https://stackoverflow.com/questions/13029299/stdvectorresize-vs-stdvectorreserve). – StoryTeller - Unslander Monica Apr 30 '19 at 12:10
  • Thank you that explains it perfectly! – Burton2000 Apr 30 '19 at 12:14
  • @Burton2000 Feel encouraged to turn your newly found insight into [an answer to your own question](https://stackoverflow.com/help/self-answer). – ComicSansMS Apr 30 '19 at 12:21
  • @ComicSansMS I was about to answer my own question but it was marked as duplicate and I can no longer leave an answer, oh well. For anyone interested it was my use of reserve() that only allocates memory but does not increase the size of the vector causing the problem. Using .reserve() and without using push_back() meant that .end() will just return the first element of the vector hence why the first code snippet doesn't work. Fix is to use resize() which will allocate memory and initialise and increase the size() of the vector. – Burton2000 Apr 30 '19 at 12:54

0 Answers0