0

Is this the right way to delete a vector of pointers?

I recently built a 3D graphics software, which works like in the code I linked. While working on optimization, it suddenly stopped working, returning 0xC0000005, no errors. I managed to track the error to a destructor that I used to automatically free memory once the object is destructed, though it did not work as planned. I recreated the code: https://code.sololearn.com/c334fwN78wa6/?ref=app Doesn't throw errors as expected. Should I delete pointers at the end of the main method or somewhere else? Also, does clearing the vector does any good?

22nd Dec 2018, 3:09 AM
voidneo
3 Answers
+ 6
You never allocated memory for the pointers yourself, and so you should not use delete. You just assigned addresses. This operation is a form of undefined behaviour, and anything can happen, ranging from a successful ignore to a segmentation fault: https://stackoverflow.com/questions/441831/calling-delete-on-variable-allocated-on-the-stack If you want to prevent memory leaks use smart pointers like unique_ptr: www.cplusplus.com/reference/memory/unique_ptr
22nd Dec 2018, 3:23 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
"This operation is a form of undefined behaviour, and anything can happen, ranging from a successful ignore to a segmentation fault" +2 for Kinshuk!
22nd Dec 2018, 6:23 AM
Babak
Babak - avatar
+ 1
I guess I'll have to study a bit more. Thanks
22nd Dec 2018, 3:31 AM
voidneo