"Rafael Anschau" wrote:
I read that you should assign null (0) to all pointers
that you call delete on.
Ummm, no. You read that you should assign NULL (not "null",
whatever that is) to pointers WHICH HAVE BEEN DELETED.
That's not at all the same as what you said.
Does that mean:
*p=0(set the value pointed to to 0).
No. That assigns 0 to the thing being pointed to, not the
pointer. If this is immediately BEFORE calling delete, it's
harmless, but accomplishes nothing. If this is AFTER calling
delete, it's an illegal memory access, and may crash your
program or your OS.
or
p=0(set the address held to zero).
Yes. Do this immediately after delete'ing any pointer.
I prefer "p=NULL;", myself. "NULL" is usually typedefed
in the compiler's headers to "(void*)0" or "0". I use
it because it makes it visually clear that a pointer
is being invalidated.
The last one is awkward for none would want a pointer
pointing to address zero
Why not??? *ALL* pointers should be set to 0 when not
in use! Then before using them, always test them to
make sure they're not NULL:
if (NULL != pAardvark)
{
*pAardvark = 37.94;
}
Otherwise, if pAardvark was never pointed at a valid
lvalue, when you do "*pAardvark = 37.94", you'll likely
crash your program, or even your OS.
(even though it compiles fine, you can´t assign
anything to it).
Of course you can! Like so:
int *PGreg = NULL; // pGreg is set to 0 here
... // some code
pGreg = &Susan; // assign address of Susan to pGreg
... // some code
if (NULL != pGreg) // PLAY IT SAFE!!!!!
{
Frank = Sam + (*pGreg); // dereference pGreg
}
I find the first still awkward because you are assigning
a value to a place you no longer use.
It's not just awkward, it's illegal memory access, aka
"general protection fault", aka "have to push reset button".
How to crash your system in 2 easy steps:
1. delete pGreg; // pGreg no points to who knows where
2. *pGreg = 0; // write to unknown memory location
What the programmer should have done instead:
1. delete pGreg; // pGreg no points to who knows where
2. pGreg = 0; // zero the pointer
But if you always assign 0 or NULL to pointers immediately
after delete'ing them, and test for (NULL != pointer) before
trying to read or write what they point to, that will help
you keep out of trouble.
--
Cheers,
Robbie Hatley
lonewolf aatt well dott com
www dott well dott com slant user slant lonewolf slant