c++ - Segmentation fault when using recursive method taking vector as input -
i'm trying make simple filter using recursion reason, keep getting these seg fault.
#include <iostream> #include <vector> #include <math.h> class filtergeneric { public: std::vector<int> filter(std::vector<int>& v, std::vector<int>::iterator i); //set i=v.begin() in main private: virtual bool g(int x) =0; std::vector<int> result; }; std::vector<int> filtergeneric::filter(std::vector<int>& v, std::vector<int>::iterator i) { if (i==v.end()) { return result; } else { if (g(*i)==true) { result.push_back(*i); i++; return filter(v,i); } else { i++; return filter(v,i); } } } class filterodd : public filtergeneric { private: bool g(int x); }; bool filterodd::g(int x) { if ((x%2)!=0) { return true; } else { return false; } } class filternonpositive : public filtergeneric { private: bool g(int x); }; bool filternonpositive::g(int x) { if (x<0) { return true; } else { return false; } } class filterfortwodigitpositive : public filtergeneric { private: bool g(int x); }; bool filterfortwodigitpositive::g(int x) { if (x>=10) { return true; } else { return false; } } int main() { std::vector<int> v; std::vector<int>::iterator it=v.begin(); (int i=0;i<20;i++) { v.push_back(pow(-1,i)*i); } std::cout<<std::endl; filternonpositive fnp; filterfortwodigitpositive ftd; filtergeneric *f1=&fnp; filtergeneric *f2=&ftd; std::vector<int> r1; std::vector<int> r2; r1=f1->filter(v,it); (it=r1.begin();it!=r1.end();it++) { std::cout<<*it<<" "; } r2=f2->filter(v,it); (it=r2.begin();it!=r2.end();it++) { std::cout<<*it<<" "; } }
the bug here:
std::vector<int> v; std::vector<int>::iterator it=v.begin(); (int i=0;i<20;i++) { v.push_back(pow(-1,i)*i); // invalidates iterators "v" } ... r1=f1->filter(v,it); // using invalidated "it"
the problem v.push_back()
invalidates iterators vector if vector needs resized. documentation:
if new size() greater capacity() iterators , references (including past-the-end iterator) invalidated. otherwise past-the-end iterator invalidated.
after correct above bug moving it
initialization after v
has been intialized, there additional bugs well.
if building g++
, can use -d_glibcxx_debug
find such bugs.
Comments
Post a Comment