by mlepage » Nov 19, 2003 @ 6:43am
SpaceManeouvres: I think I understand what you are saying, but you're writing is backwards to what you intend to say.
Let's all be clear on this:
The pointer itself has a value. What is pointed to (the data) also has a value.
Let's say the pointer lives on the stack, and the data lives on the heap.
In that case, you want to eventually free the data on the heap by calling delete. You do this by calling delete with the pointer value as argument.
This frees the memory used by the data. It does not clear the actual data. It also does not clear the pointer value.
If you subsequently call delete on that pointer again, you have performed a double deletion which is illegal. Bad things may happen, but it is your fault.
If you don't double delete, you don't have to worry about this.
If you are worried about this, you can clear your pointer value after performing the deletion. Then, you can safely delete it again, because deleting the null pointer is safe and does nothing. You haven't performed a double deletion of the allocated memory in this case.
Either way, the memory which used to hold your data likely still holds the old data, as orphaned garbage. Unless you explicitly cleared it beforehand.
Personally, I wouldn't clear data or pointers. I think that just hides underlying problems (e.g. dangling pointers or double deletion) in my code, and I'd rather fix those underlying problems.
If the pointer is on the stack, the pointer itself will cease to exist when the stack frame is popped. Of course, if you didn't clear it, it also may leave a garbage (pointer) value in memory which you should not be using.
Always be clear (in your thought, if not in your writing) about the difference between the POINTER and THE POINTER'S VALUE and WHAT IS BEING POINTED TO. They are several different things, with their own identity, their own locations, and their own lifetimes.
Basically, you should try to allocate on the stack and only use the heap if you need more flexibility with lifetime. On the stack, things automatically get cleaned up. On the heap, you must clean up manually, exactly once (not zero, not twice). In C++, this means using delete to both destroy the object (thereby perhaps doing other things and destroying other objects) and to reclaim that memory. The only exception is that it is OK to let the program terminate to release all dynamic memory (but this will not run destructors that may do important things).
Please note that you can avoid most of these issues by using the standard auto_ptr template, or boost.org's almost-standard shared_ptr template. Really, they will make your life easier.