### Deleting Vector of Pointers (need help)

Currently I am implementing the A* algorithm in C++. I have chosen to use a hybrid of a '2D vector grid' and two 1D pointer vectors to specific places in the '2D vector grid'. I have chosen to do it this way, so I can access the nodes using coordinates and also for iterating over the appropriate nodes(rather than the whole '2D vector grid').

In the below examples I have not included the full code because I deemed it irrelevant to the question.

 ``123456789101112131415161718`` ``````vector CInGame::AStarAlgorithm(vector>& resistanceMap, int startX, int startY, int targetX, int targetY, int cutOff) { vector returnVec; vector > twoDimNodes; vector openSet; vector closedSet; //lots of code here if (closestX==startX && closestY==startY) { freeSet(openSet); freeSet(closedSet); return returnVec; } }``````

And the part that creates the error...

 ``1234567`` ``````void CInGame::freeSet(vector & nodes) { for (int iter=0;iter < nodes.size();iter++) { delete(nodes[iter]); } }``````

The error is:

So my question really is, do I need to free the pointers or is it done automatically? If not then how would I do this? Thanks.
You only delete things that you created with new. If you did not use new to create the object, then you MUST NOT try to delete it... it will be cleaned up automatically.

But you have a bigger problem here.

 ``123`` `````` vector > twoDimNodes; vector openSet; vector closedSet;``````

Assuming the pointers in openSet and closedSet point to the objects in twoDimNodes.... this will only work as long as the objects do not move in memory.

The nasty gotcha here is that vector might have to move elements around in memory when you resize in order to keep all the memory contiguous. If that happens... all of your pointers in openSet and closedSet will go bad!

So if you're taking this approach... you must be absolutely sure you are not adding any more elements to your twoDimNodes vector once openSet or closedSet are populated.
Thank you for your quick response, the 'twoDimNodes' will remain static in memory so that is not a problem. Also, if I don't free the sets, then I wont get a memory leak?
If you're not using `new` to create the sets... then you do not need to `delete` them. It's that simple. delete is meant to clean up after new. Nothing more.

So no. You will not get leaks if you do not delete them (unless you created them with new)
Topic archived. No new replies allowed.