When this will be freed?

Marc Schütz" <schuetzm at gmx.net> Marc Schütz" <schuetzm at gmx.net>
Fri Apr 4 06:25:49 PDT 2014


On Wednesday, 2 April 2014 at 16:51:57 UTC, Benjamin Thaut wrote:
> Am 02.04.2014 17:57, schrieb Andrea Fontana:
>> 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.

This is unfortunately only true on x86 32-bit. For x86_64, the 
calling conventions (MS, SysV [1]) say that the first few 
parameters are passed in registers, and the same is probably true 
for other architectures.

Usually this is still safe, as the pointer will normally either 
stay in its register, or will be spilled to the stack and kept 
there as long as the function still needs to use it. But one 
might imagine a corner case where it temporarily stores the 
pointer in a global or static variable. Even if the pointer will 
not be kept by the C function longer than the call, in such cases 
you would need to keep an additional reference where the GC can 
see it.

[1] 
https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions


More information about the Digitalmars-d-learn mailing list