"Victor S. Abrash" <victor@speech.sri.com> wrote
> > Potential problem: deallocation can get tricky. Since we now
> > permit multiple pointers to the same space (instead of creating a
> > new copy each time), the programmer has to be extremely careful
> > not to deallocate the same space multiple times.
> Put an extra field in the structure, ie,
> struct Pobj {
> ... regular stuff ...
> int validity;
> }
> The validity field can be set to a magic cookie when the structure
> is valid, otherwise zero. When you deallocate an object, first set
> the validity field to zero before freeing memory. Now any other
> pointers will see that the memory they point to isn't a valid Pobj,
> and can report an error. Note that you can also re-use the
> validity field to indicate what type of object the structure holds.
I feel obligated to point out that this approach does not work: once
the memory has been freed, any stale references to the structure
should not reference a member of that structure, because even with a
"magic number" you have no way of telling if the address is valid
(e.g., processes can shrink as well as grow), nor can you determine
the probability of the occurence of the "magic number" at that
location (especially the probability of another object of the same
type, and therefore same "magic number," but with different contents
re-using those locations). This strategy inevitably leads to either
memory leakage or, worse, incorrect and/or abortive program behavior
and is not portable.
If you have the requirement for multiple references, you must first
define how those references will be used:
If the model is that the structures are generated-once and are read-
only, then you can use D. Martin's reference counting proposal (with
appropiate modification for static declarations, as per M. Fong's
suggestion).
If, however, you expect those references to be modified by any of the
program elements that make the references then you will also need the
ability to make deep copy references -- there are probably going to be
as many cases where the code making the reference wants the "modified"
reference as those who want the "original".
To be most general, support both deep-copy and reference-counting.
But again, this depends on how you want these structures to be used!
-Keith