[Gc] dangling pointer

Boehm, Hans hans.boehm at hp.com
Tue Nov 9 14:20:36 PST 2004


Continuing the side comment ...

You should be able to get the collector to throw an exception
instead of returning NULL by assigning a suitable function to
GC_oom_fn (and building at least the relevant collector files
so that exceptions can be propagated out of the collector.)

Gcj does that, for example.  As usual, this could be better
documented ...

Hans

> -----Original Message-----
> From: gc-bounces at napali.hpl.hp.com
> [mailto:gc-bounces at napali.hpl.hp.com]On Behalf Of MenTaLguY
> Sent: Tuesday, November 09, 2004 1:56 PM
> To: Hans Van den Eynden
> Cc: gc at napali.hpl.hp.com
> Subject: Re: [Gc] dangling pointer
> 
> 
> On Tue, 9 Nov 2004, Hans Van den Eynden wrote:
> 
> > The primairy goal of the GS is to avoid dangling pointers. 
> But thus the
> > GC also secure against dangling references too the stack??
> > for example:
> >
> > int& dangling_reference() {
> >     int x=3;
> >     return x;
> > }
> >
> > main{
> >     int x=dangling_reference();    //x is now dangling
> > }
> 
> That isn't legal C++.
> 
> The language specifies that local (stack-allocated) objects like
> dangling_reference()'s 'x' are destroyed when the function 
> returns.  The
> GC only governs heap-allocated objects.
> 
> The following, however, is safe, since the int would be 
> allocated from the
> garbage-collected heap:
> 
>  int &dangling_reference() {
>      int &x=*(new (GC) int(3));
>      return x;
>  }
> 
>  int main() {
>      int x=dangling_reference();
>  }
> 
> (n.b. unlike the standard operator new, which raises std::bad_alloc on
> allocation failure, gc_cpp.h's will wrongly return NULL 
> instead; in real
> code you would check for that before dereferencing a potentially NULL
> pointer)
> 
> -mental
> _______________________________________________
> Gc mailing list
> Gc at linux.hpl.hp.com
> http://www.hpl.hp.com/hosted/linux/mail-archives/gc/
> 


More information about the Gc mailing list