ldc executable crashes with this code

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Feb 3 01:57:12 UTC 2022


On Thu, Feb 03, 2022 at 01:39:33AM +0000, forkit via Digitalmars-d-learn wrote:
> On Wednesday, 2 February 2022 at 23:30:50 UTC, H. S. Teoh wrote:
> > On Wed, Feb 02, 2022 at 11:21:52PM +0000, forkit via Digitalmars-d-learn
> > wrote: [...]
> > >     char[] palindrome = cast(char[])"able was I ere I saw elba";
> > 
> > String literals are immutable by default. Casting immutable to
> > mutable is UB (Undefined Behaviour).
> > 
> > 
> > [...]
> > >     writeln(palindrome.reverse);
> > 
> > Especially because .reverse mutates its argument.  So you're
> > attempting to overwrite immutable data here. That's probably what
> > caused the crash: the literal is put in the read-only segment and
> > the OS killed the program when it tried to write to data in that
> > read-only segment.
[...]
> that explains ldc perhaps (although i don't really get it. It's cast
> to mutable and being assigned to mutable.

Assigning the literal to char[] simply creates a mutable slice of the
immutable data. That's technically UB. Then .reverse modifies the array
in-place, which means you violated immutable.


> in any case... ldc doesn't like it, but dmd is fine with this ??

UB doesn't mean a guaranteed crash, it means the result will be
implementation-dependent (and likely not what was intended). It's
possible that dmd didn't put the literal in a read-only segment, or
there may be some other reason. In any case, just because it worked by
chance does not mean it's OK to simply cast immutable to mutable and
then proceed to mutate it.


T

-- 
Let X be the set not defined by this sentence...


More information about the Digitalmars-d-learn mailing list