Sign in to follow this  
nluk

access violation when using vectors

Recommended Posts

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

Share this post


Link to post
Share on other sites
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());
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this