[comp.lang.c] pointer comparisons in dpANS C

chris@mimsy.UUCP (Chris Torek) (10/19/88)

[followups redirected to comp.std.c]
In article <8696@smoke.ARPA> gwyn@smoke.ARPA (Doug Gwyn) writes:
>The key is that you are allowed to portably compare pointers only in two
>cases:  at least one pointer is a null pointer, or both pointers are
>pointers into the same object.  This means that the fact that p1==p2 for
>pointers to distinct objects is not a problem, since such comparison is
>"undefined". ...

This point (which is true) makes me wonder about something.  Consider
a program which allocates object memory with `malloc'.  Each object has
pointers to other objects, but does not have backpointers---e.g.,
a singly linked list.  Now we have a removal routine:

	delete(listhead, obj)
		struct list **listhead;
		struct list *obj;
	{
		register struct list **p;

		for (p = listhead; *p != NULL; p = &(*p)->next) {
			if (*p == obj) {
				*p = obj->next;
				free((char *)obj);
				return;
			}
		}
		panic("object not in list");
		/* NOTREACHED */
	}
	...
		struct list *head = NULL;
		... /* put objects in the list */ ...
		delete(&head, thisobj);
		...

A perfectly ordinary routine, but it has a significant implication:
Every address returned by malloc must compare as not distinct from
every other address, lest this routine delete the wrong object.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris