[Gc] dangling pointer

MenTaLguY mental at rydia.net
Tue Nov 9 13:55:51 PST 2004

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


More information about the Gc mailing list