I have "Vertex" class pointers in a list. I want to delete these pointers and free up the memory. I deleted the pointers in the first for loop and set these pointers to 0. but just to check whether the pointers have really been deleted and set to NULL, I accessed those pointers again in the second loop.
Why am I able to access them and access the attributes and members functions in the second loop when i have set their pointers to NULL in the first loop? Have I really freed up the memory? Is "vertexList.clear()" a safe operation to do after deleting the pointers in the list?
just to check whether the pointers have really been deleted and set to NULL, I accessed those pointers again
No! You never check to make sure the computer has actually done something. When you assign things, you don't assign them twice to make sure the computer got it right, so why do this?
I have not idea why the OS didn't crash the program on line 21. Dereferencing a pointer to zero, and then accessing data in that object which doesn't exist is as illegal as it gets.
All clear() does for all STL containers is call the destructors for the objects it contains and free its own memory. Of course, destructors for primitive types (integers, floats, pointers, etc.) don't actually do anything, so if there are pointers in the contained that weren't deleted, it's a memory leak.
I have set the pointer to 0 at line 15 but at line 21 it still hold the address assigned to it by new operator. I can not figure it out why is this happening?
The way i have deleted a pointer, is it the correct way to delete it?
*Slaps forehead* Of course.
Sorry, I didn't notice this before.
On line 14, you're not zeroing the pointer in the list. You're zeroing the pointer that is the copy of the pointer in the list. Being a copy, the pointer still points to the right place, so deleting it has the same effect as deleting the pointer that really is in the list.
Now it makes sense why the system didn't crash the program. Sometimes, memory isn't freed immediately. Dereferencing an invalid pointer is still something you should never do, no matter what the circumstances.
ok, now i got it. The pointer does get deleted and the memory is freed but since the original pointer in the list still points to the same address, therefore, i am able to read the correct data (but this data can be over written any time).