Either I'm confused or the gc is

Steven Schveighoffer schveiguy at gmail.com
Mon Nov 16 21:25:03 UTC 2020

On 11/16/20 2:26 PM, H. S. Teoh wrote:
> On Sun, Nov 15, 2020 at 01:46:52PM -0800, Ali Çehreli via Digitalmars-d wrote:
> [...]
>> While I have everbody's attention, :) toStringz will come up during
>> one of my DConf presentations. I will claim that it is safe to pass to
>> a C function for their immediate consumption (but they can't save the
>> pointer).
>> So, I will claim that the following is safe and no GC collection on
>> another thread can mess this up. (The C side is not allowed to store
>> for later use but they are taking the pointer into a local variable on
>> their function call stack.)
>> nothrow extern(C) void bar(const(char) ** name) {
>>    // ...
>>    *name = makeString(42).toStringz;
>>    // ...
>> }
> [...]
> AFAIK, as long as a reference exists on the stack, you should be safe,
> because the GC does scan the stack.  But if the C side stores it
> anywhere else past the point where the on-stack reference goes out of
> scope, then you're in trouble.

I see a problem here, in that the stack is changeable by the C function.

I can imagine a situation where it removes the item from the stack to 
put it somewhere else (e.g. global memory or on the C heap) 
*temporarily*, and by the time the function exits, the pointer is no 
longer in use in C-land. Thus, the function doesn't "save the pointer".

This kind of problem would still be susceptible to the GC collecting it 
(via another thread), and so I would recommend still storing locally in 
the calling function a copy of the pointer.


More information about the Digitalmars-d mailing list