C++: vector<Foo*> with reserve(), push_back() destroying values -
the title tad confusing. here compressed version of current predicament:
classes.h:
class foo { int x; foo(): x(0) { } foo(int y): x(y) { } }; class b { vector<foo> list; b() { } }; class { vector<b> map; a() { } };
main.cpp:
vector<a> map; vector<foo*> allfoos; void initialize() { allfoos.reserve(...); } void generatemap() { (...) { a; map.push_back(a); (...) { b b; map.back().map.push_back(b); if (...) { switch (...) { case ...: foo foo(5); map.back().map.back().list.push_back(foo); allfoos.push_back(&map.back().map.back().list.back()); cout << allfoos.back()->x; // #1 break; } cout << allfoos.back()->x; // #2 } cout << allfoos.back()->x; // #3 } cout << allfoos.back()->x; // #4 } cout << allfoos.back()->x; // #5 } int main() { initialize(); generatemap(); }
when run code, able retrieve allfoos.back()
; can access members via ->
, , upon using break, mvc++ express 2013, can hover on allfoos
, given list of of elements...problem is, elements back()
element complete nonsense.
sporadically, member values become nonsensical; at #1, #2, #4, , #5, print '5'. @ #3, print gibberish number +- few million.*
after multitude of breaks, dumping of variables, etc., have determined problem push_back(...)
somehow altering location of preceding pointers, despite reserve(...)
allocating far more enough space hold many foo*
s need.
i absolutely lost. have tried hours understand why happening, no avail. have looked @ literally hundreds of similar questions, none close enough out issue (unless have been insufficient in applying solutions own problem.)
if more information necessary, can provided.
update:
here's what's stranger: if create *printdetails()
member function inside of foo
class , use allfoos.back()
@ #5 instead, of foo
's member values print perfectly fine - , same hover-over technique reveals last foo*
1 details intact.
update #2:
*i have found said changes depending on run - each time, different locations print different values, , have been unable pin down location provides consistent results. seems though have hit undefined behavior somewhere, can't seem find where...
your pointers invalidated, because when pushing values in vectors, expanded. because vector stores data contiguously, when reallocating, existing values moved place in memory. thus, raw pointers points previous, invalid locations.
if want continue populating vectors in example, should reserve proper size vectors beforehand. keep in mind keeping raw pointers vector elements bring same probleme again.
Comments
Post a Comment