More fun with toStringz and the GC
Don Allen
donaldcallen at gmail.com
Sat Aug 6 15:58:36 UTC 2022
On Saturday, 6 August 2022 at 13:40:12 UTC, Don Allen wrote:
> 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.
At the risk of over-doing this, one more thing I want to say in
the interest of clarity: the incorrect documentation led me right
into this error: "This is accomplished by ..... Leaving a pointer
to it on the stack (as a parameter or automatic variable), as the
garbage collector will scan
the stack."
I've fixed my code using addRoot/removeRoot and so far it seems
to work.
More information about the Digitalmars-d-announce
mailing list