Hi Mindaugas,

I expect pointer not to be collected, because it "lives" in variable h.

No. Not always. See below ...

What's wrong with my code?

Read below ...

PROC main()
LOCAL h
  h := myfunc( h )

You call h := myfunc( h ). h is empty so hb_gcAlloc()
is called in myfunc() and the result is stored in h.
Note that the result has got "an assinged garbage"
func hb_fctx_destructor() to it.

  debug( "1" )
  h := myfunc( h )

You call h := myfunc( h ). h is not empty so hb_gcAlloc()
is not called. But a new item is returned and stored in h.
And now the old item stored in h previously, does not belong
to any item and it is freed by GC. However a new item is not
a "garbage" item, because no hb_gcAlloc() was called for it,
so it will not be touched by GC in a future (no "garbage"
func will be called for this item).

  debug( "2" )
  h := myfunc( h )
  debug( "3" )
RETURN

#pragma begindump
#include "hbapi.h"

static HB_GARBAGE_FUNC( hb_fctx_destructor )
{
   (void) Cargo;
   fprintf( stdout, "destructor\n" );
}

HB_FUNC( DEBUG )
{
   fprintf( stdout, hb_parc( 1 ) );
   fprintf( stdout, "\n" );
}

HB_FUNC( MYFUNC )
{
   void*  ptr = hb_parptrGC( hb_fctx_destructor, 1 );

   if( ! ptr )
   {
      ptr = hb_gcAlloc( 4, hb_fctx_destructor );
   }
   hb_retptrGC( ptr );
}
#pragma enddump


--

Marek

_______________________________________________
Harbour mailing list
Harbour@harbour-project.org
http://lists.harbour-project.org/mailman/listinfo/harbour

Reply via email to