A debug class has started
WebFreak001
d.forum at webfreak.org
Mon Dec 13 12:06:53 UTC 2021
On Monday, 13 December 2021 at 11:09:18 UTC, drug wrote:
> On 13.12.2021 13:49, forkit wrote:
>> On Monday, 13 December 2021 at 09:49:05 UTC, forkit wrote:
>>> ....
>>
>> char* w = cast(char*)str.toStringz; // this seems to be the
>> solution
>>
>> class has ended ;-)
>
> That's because `str` is initialized by a literal and you can
> not change it by definition. When you call `toStringz` it
> duplicates that literal (adding terminating zero at the end)
> and the duplicate is mutable. I would recommend do not use
> `toStringz` and just make duplicate of the literal -
> https://run.dlang.io/is/vaosW0
important: toStringz _may_ do a copy with the current
implementation but nothing in the docs states it actually does
so. In fact there is commented out code where it [in the
past](https://github.com/dlang/phobos/commit/bc412e7c3fa3f124d7f2785223318b45edd4b3e6#diff-b94766ba288f9b4b05ef1a4874e26724750e614afdcddaf4c2071d0f19d91595L217) just dereferenced the memory after the string and checked if it was 0.
You should really use `.dup` if you want to mutate your string.
(You would need to duplicate anyway if you don't want an unsafe
cast)
pro-tip for bugs like this: just slap `@safe:` at the start of
every file, the compiler will tell you everything that is risky
and the bug will 9/10 times just sort itself out by fixing what
the compiler complains about. (just recently helped someone with
this again, was a 3 minute fix for a big code-base where manually
searching the issue would have taken much longer)
More information about the Digitalmars-d-learn
mailing list