Richard Tobin wrote:
Is the following program legal? (I think it is, though it relies on
the existence of intptr_t.)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
int main(void)
{
char *p;
intptr_t i;
if(!(p = malloc(10)))
abort();
strcpy(p, "hello");
i = (intptr_t)(void *)p;
i ^= 63;
p = 0;
/* plugh */
i ^= 63;
p = (char *)(void *)i;
printf("%s\n", p);
return 0;
}
This is suggested, of course, by the thread on garbage collection.
It's just the sort of program that is likely to break with a collector
of the Boehm type, because at the point commented "plugh" there is
probably nothing resembling a pointer to the malloc()ed memory, so if
there were another malloc() there it might re-use the same memory.
There's nothing obviously wrong, as far as I can see. The
same thing can be done without reliance on intptr_t by mucking
with the individual `unsigned char' constituents of `p'.
Fans of garbage collection like to label this sort of thing
"perverse," with the implication that no reasonable program would
indulge in such whimsy and so only unreasonable progams would be
broken by their garbage collectors. And yet, there are plenty
of programs that make constructive use of low-order pointer bits
that they "know" will be zeroes, using them to store a handy flag
or a small type code or something. Such programs are already not
portable (the "knowledge" of low-order zeroes is not portable),
but can be extremely practical -- and would be utterly destroyed
by the C-ish garbage collectors I've heard of.
--
Eric Sosman
es*****@acm-dot-org.invalid