Thread overview
Casting char[] ranges to string can lead to unexpected behavior
Oct 31, 2014
Domingo
Oct 31, 2014
Jesse Phillips
Oct 31, 2014
H. S. Teoh
October 31, 2014
I spent two days to find a nasty aleatory problem due to a string been assigned a range from a char[] array.

This issue on vibe.d detail it a bit more: https://github.com/rejectedsoftware/vibe.d/issues/889

I'm putting it here to call attention for other developers for this problem.

Cheers !
October 31, 2014
On Friday, 31 October 2014 at 02:04:00 UTC, Domingo wrote:
> I spent two days to find a nasty aleatory problem due to a string been assigned a range from a char[] array.
>
> This issue on vibe.d detail it a bit more: https://github.com/rejectedsoftware/vibe.d/issues/889
>
> I'm putting it here to call attention for other developers for this problem.
>
> Cheers !

To recap, the issue is that a char[] buffer is being overridden while a immutable reference was created to the same data (string).

Essentially you can't cast a char[] to string unless it is the only reference that will remain. Even so, I wouldn't recommend cast in those cases and instead use std.exception.assumeUnique to better state the assumption made.

http://dlang.org/phobos/std_exception.html#.assumeUnique

If the mutable reference will remain the duplicating the char[] is necessary and the reason for .idup.
October 31, 2014
On Fri, Oct 31, 2014 at 02:03:58AM +0000, Domingo via Digitalmars-d-learn wrote:
> I spent two days to find a nasty aleatory problem due to a string been assigned a range from a char[] array.
> 
> This issue on vibe.d detail it a bit more: https://github.com/rejectedsoftware/vibe.d/issues/889
> 
> I'm putting it here to call attention for other developers for this problem.
[...]

The problem is not caused by slicing, it's caused by casting a slice of char[] to string.  Casting char[] to string is a dangerous operation, because you're operating outside the type system. string is immutable(char)[], but the original buffer is char[]. Casting it to string means you're claiming that nobody will modify the char[] afterwards... but if somebody does modify it later, then you have violated immutability and broken the type system.

Generally, I recommend using to!string(...) instead of a cast, since to!string will make a copy of the data if it's not already immutable. Casts always require extra care because the type system can no longer help you catch mistakes.


T

-- 
The diminished 7th chord is the most flexible and fear-instilling chord. Use it often, use it unsparingly, to subdue your listeners into submission!