Tak-Shing Chan wrote:
On Fri, 1 Sep 2006, Ben Pfaff wrote:
>Tak-Shing Chan <t.****@gold.ac .ukwrites:
>>On Fri, 1 Sep 2006, Ben Pfaff wrote:
Tak-Shing Chan <t.****@gold.ac .ukwrites:
(3) In general, writing pointers to files is always
nonportable . So, I am not sure why you are posting this in a
group that values portability.
Writing a pointer to a file is *not* always non-portable. It is
portable to write a pointer to a file, read it back within the
same run of the program, and then use the pointer (as long as the
lifetime of the associated memory has not been reached).
An intervening realloc could mess it up.
realloc terminates the memory's lifetime.
I don't think so. The new object might overlap with the old
one. Perhaps you meant ``object'' rather than ``memory''?
Tak-Shing
You raise a very importaznt point here, that furthers the arguments for
an automatic garbage collector.
When you do a
q = realloc(p,2*n);
after a successful realloc the p pointer and ALL THE ALIASES you have
done for that object, "including but not limited to":
o structures that contain that pointer in some field
o functions, that hold aliases to that object address in the stack
in their parameter list
o other local variables that use pointers based on that pointer,
for instance p+5 or &p[78]
ARE ALL INVALID and must be ALL invalidated!!!
Manually.
Using the GC you do
q = GC_malloc(2*n);
if (q) {
memcpy(q,p,n); // Copy the old object
p = NULL;
}
else
//No more memory Handle error
Now q contains the reallocated object but the old
storage will be freed only (and only then) when there are no
pointers to it!
Obviously, if you are 100% sure that there are no aliases to
the object, you can use GC_realloc();
But this is not without problems too, since the aliases will
point to old object copies and not to the good one, and
those copies will NOT be updated.
This can be a problem, or may be is harmless, it depends on the
application. For instance if the new object is updated by
adding members to it (a table of structures for instance) it
can be OK to keep the old shorter version, but that could also be dangerous.
In the case of
struct {
int nbOfElements;
T data;
};
after a realloc of "data", the old pointer stored elsewhere
will be utterly wrong after a realloc, and a GC solution could make
the problem even worse.
But this is a matter of discipline of alias usage and discipline
of pointer usage in general.
Another thread of discussion.
Yes, memory management *is* tricky.