Search code examples
arraysc++11vectorcopystl-algorithm

C++11 Segmentation Fault trying to copy array (<algorithm>) into vector dynamically


When I try to copy a fixed size array to a default constructed vector, I get a segfault. I'm confused because I always thought vectors are flexible containers which adjust their size to dynamic data they absorb. If I allocate space for the vector in compile time copying works but how can I copy this array into a vector without allocating a size at compile time?

int numbersArr[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
vector<int> NumbersVec; //Default constructor
// vector<int> NumbersVec(10); If I allocate the memory in compile time it works

copy(numbersArr, numbersArr + 10, NumbersVec.begin()); //Segmentation fault (core dumped)

Solution

  • The destination array needs to have sufficient number of elements as the source. Therefore use below to add new elements as necessary.

    #include <iterator>
    copy(numbersArr, numbersArr + 10, back_inserter(NumbersVec));
    

    `