I am curious as to what part of the dereferencing a NULL ptr causes undesired behavior. Example:
// #1
someObj * a;
a = NULL;
(*a).somefunc(); // crash, dere
you need to know more about anotherfunc() to tell what will happen when you pass it null. it might be fine, it might crash, depends on the code.
I agree with Buck, in that in many cases it would be nice if calling a instance function on null
resulted in null
. However, I don't think that it should be the default. Instead there should be another operator (I'll leave what that is up to someone else, but let's say it's ->>
).
One issue in C++, for instance, is that not all return types can be null
anyway, such as int
. So a call to a->>length()
would be difficult to know what to return when a
itself was null
.
Other languages where everything is a reference type, you would not have this problem.
Finally, Buck, what everyone else is saying is the way things are, especially for the C++ language: Dereferencing is a mechanical operation in most languages: It must return something of the same type and null
is typically stored as zero. Older systems would just crash when you tried to resolve zero, newer ones would recognize the special nature of the value when the error occured.
Also, these lower level languages cannot represent null
as an integer (or other basic data types), so you could not in general deference null
as null
in all cases.
Tom's comment is correct, I did not initialize correctly therefore the question is ambiguous at best yet most everyone directly answered my question, I unwittingly submitted the question while not logged in (sorry I'm new to stackoverflow) so can someone with editing powers update the OP?
// #2
someObj * b;
anotherObj * c = new anotherObj(); //initialize c
b = NULL;
c->anotherfunc(*b); // *b is in question not the c dereference
It would still cause a crash, but that's not necessarily undesired behaviour. Part of the usefulness of NULL
is that, on most platforms, it points to memory that is explicitly inaccessible to your application, and causes a segmentation fault (or access violation) the very moment you try to dereference it.
Its purpose is to explicitly mark the contents of pointers as invalid.