Garbage collector returning pointers

Robert M. Münch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 14 11:26:34 PDT 2015


Hi, I have a question about how the GC handles this case:

export extern(C) char* foo(){
  char[] x = "This is a dynamic D string.".dup;

  return(cast(char*)x);
}

Since x is "pointer to array data & length" if it goes out of scope, 
it's destroyed and the last reference to the array data is gone. Hence, 
the GC could kick in and free the array data. Is this correct?

Or will the GC know, that there was a pointer to the array data 
returned and hence a new reference exists as long until someone tells 
the GC that the pointer is no longer used?

My situation is, that the returned pointer is used to copy the result 
to some interpreter internal state. Depending on the answers above, 
there could be a short time where the memory state is "collectable" 
before the coyping was finished.

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list