What is wrong with this program?

Guy Harris guy at sun.uucp
Mon Aug 12 06:33:22 AEST 1985


> >
> >Sample output:
> >	
> >     	tty03                 /*  This shows that data->ut_line isn't null */
> >bruce	(null)	492299400     /*  So what's the problem in this line?      */

> Are you *sure* it really isn't null?

Yes, he's sure; "printf" prints "(null)" if the pointer it's handed is
itself null, not if it points to a null string.  If the code posted was the
entire program, and not just a fragment, the problem is, as Chris Torek
pointed out, that the guy declared a pointer to the "utmp" structure, and
used it, without making it point to anything.  He should just have declared
a structure and used it directly.

Confusion about structures and pointers to them seems to be common.

	struct foo {
		...
	} bar;
	struct foo *bletch = &bar;

	<code using "bletch">

is not necessarily better than

	struct foo {
		...
	} bar;

	<code using "bar" directly>

and is more obscure (since the pointer isn't necessary, and the person
reading the code may waste time figuring out that fact).  It may have some
benefit if 1) "bletch" is in a register, 2) you have addressing modes like
"short_displacement(Rn)", and 3) you *don't* have addressing modes like
"short_displacement(SP)" or "short_displacement(FP)" or the displacement of
the members of the structure from the SP or FP isn't "short".  However, this
is uncommon (the PDP-11, VAX, M68000, Z8000 and CCI Power 6 families use a
general register as FP/SP, so it makes no difference; the NS32xxx family
supports the use of "displacement(FP)" in the same way it supports
"displacement(Rn)"; I suspect the WE32xxx family, and most of the other
machines out there do one or the other also; the 80*86 family looks like it
can with the proper choice of register to implement FP), and I'd be
surprised if it made enough difference to make the obscure code (which isn't
likely to run any faster on the machines mentioned above) worth it.
Nevertheless, I've seen this kind of thing often enough that I suspect it's
due to misunderstanding of C.

I've also seen code like that in the original article, where the user seems
to be under the impression that declaring a pointer automatically declares
something for it to point to *and* sets it to point to that - I've seen it
less, though, because it simply doesn't work.

	Guy Harris



More information about the Comp.lang.c mailing list