if (pointer) command

guy at sun.UUCP guy at sun.UUCP
Mon Sep 8 08:24:00 AEST 1986


(This discussion has ceased to be related to UNIX; it is now a discussion of
C, so it is being moved to net.lang.c.)

> > It DOESN'T???  Gee, then maybe you have a busted malloc().  If malloc()
> > fails, it should return the null pointer.  That is what is being tested in
> > the clause 'if(p=malloc(strlen(s)+1))'.  As so many people have expounded
> > in net.lang.c:  a null pointer is semantically the same as zero in the C
> > language (except for sizeof(), should pointers exist of sizes other than
> > sizeof(int)).

> But if a pointer is 4 bits and an int is 2 bits (some 68000
> implementations), you'll get spurious failures if the pointer returned by
> malloc is a multiple of 0x10000!

Not if you've declared "malloc" to return a "char *", you won't.  All C
compilers will generate equivalent code for

	extern char *malloc();
	char *p;
	unsigned int i;

	if (p = malloc(i))
		foo();

and

	extern char *malloc();
	char *p;
	unsigned int i;

	if ((p = malloc(i)) != 0)
		foo();

Any compiler that does *not* generate equivalent code in these two cases is
not a C compiler; it compiles some other language that may look like C in
some ways, but is not C.  If it was intended to be a C compiler, it has a
bug.  (Any compiler that does not generate equally efficient code for these
two constructs is *also* broken, since they both mean the same thing in C.)

If you haven't declared "malloc" to return a "char *", this code will rarely
if ever work on a machine where "char *" and "int" have different sizes,
regardless of whether "malloc" succeeds or fails.
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy at sun.com (or guy at sun.arpa)



More information about the Comp.lang.c mailing list