More fun with toStringz and the GC

Don Allen donaldcallen at gmail.com
Sat Aug 6 13:40:12 UTC 2022


On Saturday, 6 August 2022 at 02:14:24 UTC, Steven Schveighoffer 
wrote:
> On 8/5/22 8:51 PM, Don Allen wrote:
>
>> And this, from Section 32.2 of the Language Reference Manual:
>> ````
>> If pointers to D garbage collector allocated memory are passed 
>> to C functions, it's critical to ensure that the memory will 
>> not be collected by the garbage collector before the C 
>> function is done with it. This is accomplished by:
>> 
>>      Making a copy of the data using core.stdc.stdlib.malloc() 
>> and passing the copy instead.
>>      -->Leaving a pointer to it on the stack (as a parameter 
>> or automatic variable), as the garbage collector will scan the 
>> stack.<--
>>      Leaving a pointer to it in the static data segment, as 
>> the garbage collector will scan the static data segment.
>>      Registering the pointer with the garbage collector with 
>> the std.gc.addRoot() or std.gc.addRange() calls.
>> ````
>> I did what the documentation says and it does not work.
>
> I know, I felt exactly the same way in my post on it:
>
> https://forum.dlang.org/post/sial38$7v0$1@digitalmars.com
>
> I even issued a PR to remove the problematic recommendation:
>
> https://github.com/dlang/dlang.org/pull/3102
>
> But there was pushback to the point where it wasn't worth it. 
> So I closed it.

As I said in my previous post, the documentation issue really 
needs to be addressed.

I do realize now that I *assumed* that what I did was going to 
result in a stack reference to the c-string I was trying to keep 
alive. Bad assumption, obviously. But I think the point is that 
there is a simple, reliable mechanism -- addRoot, removeRoot -- 
that works and the documentation should say that and only that. 
Walter said this in his 9/25/21 post: "Use GC.addRoot() to keep a 
reference alive. That's what it's for.
". That's all that's needed. All the rest leads people like me 
who don't think like a compiler to make the mistake I made.


More information about the Digitalmars-d-announce mailing list