C++: "Error: Pointer being freed was not allocated" when handling large lists -
i trying process data in std::vector made of 2d points; basically, need check whether or not points are, directly or indirectly through point, linked relationship don't think needs detailed here.
in order process data properly, copied data vector , used lists faster handling.
i wrote following 2d vector class:
class float2d { public: float x, y; float2d(): x(0), y(0) {} float2d(int a, int b): x(a), y(b) {} bool checkstuffwith(float2d &u); // math };
the code used process data looks this:
bool checkstuffinvector(vector<float2d> const &data) { if (data.size() < 2) return true; // copy data in list, thinned out progressively list<float2d> data_copy(data.begin(), data.end()); // points used checkstuff remaining points in data_copy list<float2d> processed_data; // choose arbitrarily last element compare others processed_data.push_back(data_copy.back()); data_copy.pop_back(); list<float2d>::iterator it1; list<float2d>::iterator it2 = data_copy.begin(); while (!processed_data.empty()) { it1 = processed_data.begin(); if (it1->checkstuffwith(*it2)) { // *it2 fulfills relationship // remove point data_copy // , put in processed_data processed_data.push_back(*it2); data_copy.erase(it2); } else { // move on next point process it2++; } if (it2 == data_copy.end() && !data_copy.empty()) { // checked necessary stuff *it1 // no need keep in processed_data processed_data.pop_front(); it2 = data_copy.begin(); } else if (data_copy.empty()) { break; } } return data_copy.empty(); }
this runs fine relatively low values data.size()
, need work bigger values. when vector's size 1,000,000, following runtime error:
malloc: *** error object 0x7fac0e341240: pointer being freed not allocated
i can't figure out comes from. overlooked something, can't see is; figured outsider's might :)
i want point out such problem handled using tree structure, because of size of problem, might cause tree's height big (thus, risk of stack overflow?) , fact want runs fast, thought i'd better off doing way.
thanks in advance!
when data_copy.erase(it2)
invalidate iterator it2, dereference iterator in next iteration of while loop. ub.
i suggest resolve replacing erase line this
it2 = data_copy.erase(it2)
which replace it2 iterator valid iterator pointing next element or data_copy.end() if list empty.
Comments
Post a Comment