c++: a class accessing an std::vector of main class by pointers goes wrong -
i'm building c++ project vs2012 express, platform toolset v100, , openframeworks 0.7.4.
i have class called namerect
, part of .h
file:
void config(int cx, int cy, int cw, int ch, std::string cname) { x = cx; y = cy; w = cw; h = ch; name = cname; dead = false; } void branch(int iterants, std::vector<namerect> *nrs) { (int = 0; < iterants; i++) { namerect nnr; nnr.config(x + w, y - iterants * h / 2 + * h, w, h, "cb"); children.push_back(nnr); nrs->push_back(nnr); } } void render() { if (!dead) { ofsetcolor(ofrandom(0, 255), ofrandom(0, 255), ofrandom(0, 255), 0); ofrect(x, y, w, h); } }
and there's code in testapp.cpp
:
//-------------------------------------------------------------- void testapp::setup(){ ofsetwindowshape(800, 600); nr.config(0, 300, 50, 10, "cb"); nrs.push_back(nr); } //-------------------------------------------------------------- void testapp::update(){ if (ofrandom(0, 50) <= 1 && nrs.size() < 100) { (int cnri = 0; cnri < nrs.size(); cnri++) { if (ofrandom(0, nrs.size() - cnri) <= 1) { nrs[cnri].branch(2, &nrs); } } } } //-------------------------------------------------------------- void testapp::draw(){ (int di = 0; di < nrs.size(); di++) { nrs[di].render(); } }
and when build (succeeds) project , run it, gives me such error:
i take @ local variables watch , shows such large integer values!
what problem?
branch() modifying vector array passed in second parameter.
this means when call nrs[cnri].branch(2, &nrs) testapp::update() underlying array structure modified. lead unpredictable results , surely cause access violation.