Re: Proper way to check malloc return
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 26 May 2010 17:22:14 -0700
gordonb.f6x43@xxxxxxxxxxx (Gordon Burditt) writes:
andy_P <andypanov@xxxxxxxxx> wrote (and Gordon Burditt refused to
acknowledge):
I am still convinced that pointer comparison should be used in C
instead of if(ptr) form.
If that statement is for stylistic reasons, you are entitled to your
opinion.
If that statement is for alleged portability reasons, you are wrong.
Any compiler that gets that wrong is so broken you will have a lot of
problems compiling existing code.
I'd say that any compiler that gets that wrong is not a C compiler,
and you're not likely to find it unless you're in the early stages
of implementing it yourself.
The C standard does not require a null pointer to be represented[snip]
as the bit pattern 0xdeadbeef, even on 32-bit machines, nor does
it require a null pointer to be represented as 0xdeadbeefdeadbeef
on 64-bit machines. However, if it does have that 32-bit representation,
all 3 sets of code:
if (ptr) { ... }
and
if (ptr != 0) { ... }
and
if (ptr != NULL) { ... }
may all generate the same code, which might be:
In any case, a good compiler will generate identical code for all three
code fragments. The behavior of the C code does *NOT* depend on whether
the internal representation of a null pointer is or isn't all-bits-zero.
Ah, but his argument wasn't based on the representation of a null
pointer, it was based on the assumption that "if (ptr)" performs
an implicit conversion of ptr to some integral type. If that
assumption were correct, he'd be correct, since the result of such
a conversion is implementation-defined. But the assumption was
incorrect, as I explained a while ago; "if (ptr)" compares ptr to
0, which results in 0 being converted to the pointer type, which
is a well defined operation.
[As always, permission to quote my Usenet postings is granted if
and only if they are properly attributed.]
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: Proper way to check malloc return
- From: andy_P
- Re: Proper way to check malloc return
- References:
- Proper way to check malloc return
- From: Billy Mays
- Re: Proper way to check malloc return
- From: andy_P
- Re: Proper way to check malloc return
- From: Richard Heathfield
- Re: Proper way to check malloc return
- From: andy_P
- Re: Proper way to check malloc return
- From: Gordon Burditt
- Proper way to check malloc return
- Prev by Date: Re: Proper way to check malloc return
- Next by Date: Re: Typecast clarification
- Previous by thread: Re: Proper way to check malloc return
- Next by thread: Re: Proper way to check malloc return
- Index(es):
Relevant Pages
|