Search code examples
c++c++11gccstdvectorstl-algorithm

C++11 gcc 4.9.2 algorithm partition_copy() results in SIGABRT, works with back_inserter


I am trying to partition a vector into even and odd numbers. I resized both output containers to ensure that they're big enough - but partition_copy still results in SIGBART for me, even though it works when I use back_inserter. Here is my code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool is_even(int num)
{
    return (num % 2 == 0);
}

void print_vector(const vector<int> & VecRef)
{
    cout << endl;
    cout << "Contents of the vector is : " << endl;
    for (auto it = VecRef.begin(); it != VecRef.end(); ++it) {
        cout << "[" << it - VecRef.begin() << "] : " << *it << endl;
    }
}

int main() 
{
    vector<int> NumbersVec;

    for (int cnt = 1; cnt < 10; ++cnt)
        NumbersVec.push_back(cnt);

    vector<int> EvenVec, OddVec;
    unsigned countEven = count_if(NumbersVec.begin(), NumbersVec.end(), is_even);

    cout << "Evens : " << countEven << endl; //Prints 4
    cout << "Odds : " << NumbersVec.size() - countEven << endl; //Prints 5

    EvenVec.resize(countEven);
    OddVec.resize(NumbersVec.size() - countEven);

    partition_copy(NumbersVec.begin(), NumbersVec.end(), EvenVec.begin(), OddVec.end(), is_even);

    // partition_copy(NumbersVec.begin(), NumbersVec.end(), back_inserter(EvenVec), back_inserter(OddVec), is_even); This works...

    print_vector(EvenVec);
    print_vector(OddVec); // <== this one crashes

    return 0;
}

The resulting output with backtrace is below:

Evens : 4
Odds : 5

Contents of the vector is : 
[0] : 2
[1] : 4
[2] : 6
[3] : 8

Contents of the vector is : 
[0] : 0
[1] : 0
[2] : 0
[3] : 0
[4] : 0
*** Error in `./82-AlgorithmSort': free(): invalid next size (fast): 0x0000000000fb1030 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x7198e)[0x7f849992c98e]
/usr/lib/libc.so.6(+0x76dee)[0x7f8499931dee]
/usr/lib/libc.so.6(+0x775cb)[0x7f84999325cb]
./82-AlgorithmSort(_ZN9__gnu_cxx13new_allocatorIiE10deallocateEPim+0x20)[0x404712]
./82-AlgorithmSort(_ZNSt16allocator_traitsISaIiEE10deallocateERS0_Pim+0x2b)[0x404579]
... snip ...
Aborted (core dumped)

Solution

  • You're passing the wrong iterator:

    partition_copy(NumbersVec.begin(), NumbersVec.end(), 
                   EvenVec.begin(), OddVec.end(), is_even);
                                          ↑↑↑↑↑↑
    

    You meant:

    partition_copy(NumbersVec.begin(), NumbersVec.end(), 
                   EvenVec.begin(), OddVec.begin(), is_even);