access violation when using vectors

Started by
2 comments, last by Trenki 16 years, 2 months ago
hello I have a opengl canvas class, which contains a vector that holds a list of shape objects that gets displayed. Anyways the problem is when I try to remove the shape I get an access violation void GLcanvas::addShape(GLshape* x) { theDisplayLists.push_back(x); //will be used to remove object theDisplayLists[numInList]->position = theDisplayLists.begin(); numInList++; } //where x will be (shape class)->position void GLcanvas::removeShape(GLshape** x) { theDisplayLists.erase(x); //access violation numInList--; } I'm using borland builder 6
Advertisement
Not sure if you noticed it but you added a pointer to the shape to the list and you're trying to remove a "pointer to a pointer" from the list... That's whats causing your access violation.
Ok, first off, and this doesn't have anything to do with your problem, the numInList variable is pointless, since std::vector give a size() member function that will tell you how many elements are in the vector.

As for your actual problem, you're probably supplying an invalid value for your element address that isn't in the actual vector. Consider instead using the value of the GLshape pointer and using the remove-erase idiom to remove the item. Ex:
void GLcanvas::removeShape(GLshape* x){  theDisplayLists.erase(std::remove(theDisplayLists.begin(), theDisplayLists.end(), x),                        theDisplayLists.end());}

Why do you keep track of the number of elements with your own variable? std::vector proviced the size() member function.

Also you pass a GLShape* to the add function and a GLShade** to the remove function.

Also theDisplayLists[numInList]->position = theDisplayLists.begin(); smells. It possibly accesses the vector at a out of range position. And you should not store iterators to your objects anywhere since they can become invalidated if you add new elements to the vector.

This topic is closed to new replies.

Advertisement