ldc executable crashes with this code

Steven Schveighoffer schveiguy at gmail.com
Thu Feb 3 13:19:03 UTC 2022


On 2/2/22 10:07 PM, Tejas wrote:
> On Wednesday, 2 February 2022 at 23:21:52 UTC, forkit wrote:
>> Any reason why compiling this with ldc would cause the exe to crash?
>>
>> Compiling with DMD (using either declaration of palindrome works just 
>> fine though)
>>
>>
>> // ----
>>
>> module test;
>>
>> import std;
>>
>> void main()
>> {
>>     char[] palindrome = cast(char[])"able was I ere I saw elba";
>>
>>    //char[] palindrome = 
>> ['a','b','l','e','w','a','s','I','e','r','e','I','s','a','w','e','l','b','a']; 
>>
>>
>>     writeln(palindrome);
>>
>>     // note: The line below causes the exe to crash when compiled with 
>> ldc
>>     // but only if using the first version of palindrome.
>>
>>     writeln(palindrome.reverse);
>> }
>>
>> // ---
> 
> This segfaults even on `dmd 2.098.0` for me.
> Clearly implementation defined behavior.

Note that on Windows DMD, string literals are not marked as Read only. 
This is legacy from the D1 days when strings were actually typed as 
`char[]`. In fact, if you mutate the data, then it mutated the literal, 
so if you used the literal later, then you got the mutated version!

e.g.:

```d
auto str = "foo";
str[0] = 'b';
writeln("foo"); // outputs "boo"
```

On Linux, the literals were marked as ROM, and so you get a runtime 
fault. If you search back to the D1 days you can find posts about this 
difference between Windows and Linux.

I'm assuming LDC and GDC follow the same practice as Linux DMD.

-Steve


More information about the Digitalmars-d-learn mailing list