"DHOLLINGSWORTH2" <DH*************@cox.net> writes:
"G Fernandes" <ge**********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com... Comparisons of pointer variables to 0 are automatically converted to
comparisons to NULL (which can be represented at the bit level but
something non-zero).
But how about using !ptr or ptr in test conditions (of loops, if or ?:)
?
For example:
char *ptr = malloc(1);
if(!ptr)
{
/*code*/
}
It works for me, but I happen to know that my implementation uses zeros
to represent NULL. Will this be portable to systems that don't have
zero based NULL?
Thanking in advance.
For the most part it will work. However, sometimes the case comes up where
ptr != 0 , and ptr is not a valid pointer. Don't assume that all invalid
pointers are zero, only that all zeros are null.
First of all, "if (!ptr)" and "if (ptr != 0)" are exactly equivalent;
they both test whether the pointer is non-null.
It's guaranteed that malloc() returns either a null pointer or a valid
pointer (unless memory has been corrupted by something that invoked
undefined behavior, in which case all bets are off anyway).
You might as well assume that any non-null pointer is valid, because
there's no way in standard C to determine that a non-null pointer is
invalid. You just have to make sure that you don't use any invalid
pointers in the first place.
Section 5 of the C FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
discusses null pointers; it's highly recommended.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.