Garbage collector returning pointers
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Mar 14 13:45:21 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);
> }
>
> 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.
As long as the pointer remains on the stack or in a register, the
GC will keep the allocation alive. But if your C code stores the
pointer on the C heap or in a global, the GC won't know anything
about it and can free it.
More information about the Digitalmars-d-learn
mailing list