Garbage collector returning pointers
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Mar 14 11:49:16 PDT 2015
On Saturday, 14 March 2015 at 18:26:34 UTC, Robert M. Münch wrote:
> 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);
> }
Returning `x.ptr` would look a little nicer.
>
> 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?
No.
> 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?
Yes. The returned pointer is a reference. Once that reference is
gone, the GC can collect the array. You don't need to explicitly
inform the GC when you're done with the pointer.
> 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.
I think you're safe.
More information about the Digitalmars-d-learn
mailing list