pointer comparisons in dpANS C
Chris Torek
chris at mimsy.UUCP
Thu Oct 20 00:06:54 AEST 1988
[followups redirected to comp.std.c]
In article <8696 at smoke.ARPA> gwyn at 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 at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list