When this will be freed?

Benjamin Thaut code at benjamin-thaut.de
Wed Apr 2 09:51:57 PDT 2014


Am 02.04.2014 17:57, schrieb Andrea Fontana:
> On Wednesday, 2 April 2014 at 15:53:52 UTC, Jacob Carlborg wrote:
>> On 2014-04-02 17:45, Andrea Fontana wrote:
>>
>>> auto example(char* test) { return toStringz(to!string(test) ~ "
>>> world!"); }
>>>
>>> When that return string will be freed?
>>
>> When there is no reference left to the string, the garbage collector
>> is free to collect it when it chooses to.
>>
>
> That's expected.
>
>>> What about:
>>>
>>> extern(C) auto example(....)
>>
>> Same as above, extern(C) does not change how memory is collected. If
>> it is a C function, then it depends entirely on that particular function.
>
> I mean: if it is an exported function (of a shared library) what
> happens? There's no reference kept anywhere (in D). So if I'm right it
> could be freed immediatly by GC. Right?
>

If you pass that string to a C function, there is a reference on the 
stack. So this string will not be freed until that C-function returns. 
If that C-Function returns, it is very likely however that this was the 
only reference and the string will be freed the next time the garbage 
collector runs.

Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list