Re: Garbage collection in C++
On Nov 20, 9:49 am, Hendrik Schober <spamt...@gmx.de> wrote:
James Kanze wrote:
On Nov 19, 5:10 am, Keith H Duggar <dug...@alum.mit.edu> wrote:
[...]
C++
Foo * x = new Foo() ;
//in a code far far away a reference is squirreled away
Foo * y = getX() ;
//time passes, we want x to never be used again
delete x ;
//in a code far far away the squirreled digs up his nut
y->activate()
Java
Foo x = new Foo() ;
//in a code far far away a reference is squirreled away
Foo y = getX() ;
//time passes, we want x to never be used again so what do
//you put here to indicate this? Roll your own "zombify"?
//in a code far far away the squirreled digs up his nut
y.activate()
In the C++ version, Purify (or similar) will catch the
dangling pointer or if it sneaks by (as you say "mistakes
will creep in") you have at least some a chance that the
code cores and reveal the error. In Java (and in GC in
general?) you will never know. What am I missing?
Purify will catch the error, but delivered code doesn't run
under Purify, so if the error doesn't show up in your test
cases, you're hosed without garbage collection; [...]
I don't think this can be discussed that generally. It
might just be that accessing the object at this time
might do something blatantly stupid and by having GC
allowing it, instead of the app core dumping it might
be much worse.
The problem is that in real life, the application didn't core
dump. The memory was reallocated as a buffer, where user input
was written. And the user designed his input so that it
corresponded to a vptr which pointed to malicious code, and
breached security when the dangling pointer was used.
With garbage collection, the "destructor" sets the vptr to an
invalid pointer. And since the memory can't be reallocated as
long as it is reachable, the invalid pointer stays set, and the
crash is guaranteed (which is what you want).
What it comes down to is that we're replacing undefined behavior
with defined. You may not like what the defined behavior is,
out of the box, but you can intervene to make it whatever you
want. Where as undefined behavior is, well, undefined.
[...]
OTOH, there is the argument that GC only deals with one
resource (although admittedly the one that's probably most
common), but doesn't do anything to help you with all the
others.
I'll admit that I don't understand this argument. Obviously,
garbage collection deals with only one resource. But you need
different solutions for different resources; what makes garbage
collection useful is that it deals transparently with the only
resource nine tenths of your classes are concerned with. So you
have less work to do.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34