Re: Avoiding dangling pointers.
Rafael Anschau wrote:
If you set p=0, you are not pointing nowhere, and I found that weird. But
it actualy makes sense, it??s better to have the program crash
right away if something tries to write on it, than to have it write fine
on some dark zone of heapland which you will never be able to reach again.
Reduces debugging time.
Actually, you missed a point: if the value of a pointer is zero, this is a
special signal value which means that it doesn't point to an object. Of
course, trying to use the object it points to (which doesn't exist) will
result in a crash, but even more important is the fact that you can _check_
if the pointer is zero and thus prevent the crash!
int* i = new int(42);
delete i;
/* 'i' now points to nowhere ('dangling pointer'), but there is no way to
detect that it doesn't point to an object. */
i = 0;
// Now you again have a usable state that you can work with
Note that a good way to avoid dangling pointers is to use so-called 'smart
pointers', which make reasonable sure that they are never dangling and also
achieve defined error signalling behaviour even in the face of typical
programming errors.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Michael W??hrmann, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]