Skarmander said:
Copy the bytes of the pointer to an array of unsigned char. Copy back
when done. The standard requires this to work. (The first stage, at
least. I must admit I haven't looked closely at the guarantees for the
second stage.)
Simply copying the bytes of a pointer to an array of unsigned char
isn't likely to fool a garbage collector, unless the garbage collector
makes assumptions about the types of objects (which would require a
great deal of chumminess with the compiler).
My understanding is that GC works by scanning memory for things that
look like pointers, and marking anything pointed to by those pointers
as in-use and therefore not available for deallocation. This can
result in some false positives, if something that's not a pointer
happens to contain a bit representation that matches a valid pointer
value. As far as I know, this isn't a major problem in practice.
Copying the bytes of a pointer *and re-ordering them* would fool the
garbage collector (as long as the object from which you copied them is
destroyed).
I can imagine an application that, for security reasons, keeps certain
data structures encrypted most of the time, decrypting them only when
necessary.
I can also imagine an application storing pointers in a file, to be
retrieved later during the same execution of the same program. This
isn't likely to be useful unless you've built some very large
pointer-intensive data structures, and you don't have enough resources
to keep them all in memory all the time.
I presume most garbage collectors provide a mechanism to temporarily
or permanently disable them, either completely or for a given data
structure. A program that does the kind of exotic pointer
manipulation I describe *and* that needs to work in a
garbage-collecting environment would have to take advantage of this
feature.
Also, garbage collection can be impractical in some environments. A
real-time system can't afford to wait for the GC system to analyze
memory while it's trying to meet a hard deadline.