Implicit static->dynamic arr and modifying

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 7 15:22:49 PDT 2014


On Wednesday, 7 May 2014 at 20:09:22 UTC, H. S. Teoh via 
Digitalmars-d-learn wrote:
> On Wed, May 07, 2014 at 06:31:15PM +0000, Rene Zwanenburg via 
> Digitalmars-d-learn wrote:
>> On Wednesday, 7 May 2014 at 15:41:19 UTC, Nick Sabalausky 
>> wrote:
>> >On 5/6/2014 6:46 PM, Rene Zwanenburg wrote:
> [...]
>> >>struct S
>> >>{
>> >>    @safe:
>> >>    string str;
>> >>
>> >>    this(string data)
>> >>    {
>> >>        import std.digest.md;
>> >>        str = md5Of(data).toHexString(); // Oops...
>> >>    }
>> >>}
>> >
>> >That must be a terribly subtle one, I'm not seeing the 
>> >problem at
>> >all.
>> >
>> >I get that md5Of returns a static array, and then a slice of 
>> >it gets
>> >passed to toHexString, but AIUI toHexString finishes (and 
>> >returns a
>> >newly allocated string) before the temporary static array 
>> >leaves
>> >scope.
>> 
>> toHexString has an overload that takes a static array and can
>> therefore return a static array (the length is known to be 
>> twice the
>> input length). In essence it's the same bug as directly 
>> storing the
>> result of md5Of, but this was the exact line that was causing 
>> me
>> grief. Indeed, it looks innocent enough..
>> 
>> So, toHexString returns a static array, which can be implicitly
>> assigned to a member slice. In @safe code. I was horrified ;). 
>> Imo
>> it's one of the most serious violations of D's safe by default
>> principle.
>
> Ouch!! Wow, that's really nasty. :-(  It totally went by me, 
> even though
> I've been bitten before by the variadic ctor bug.
>
>
> T

FYI, I think this is one of the biggest implicit static 
array=>dynamic array bug you can do.

What's more, slicing of an rvalue static arrays is wrong 100% of 
the time. It's taking the address of a temporary. And the 
compiler should be able to catch it easy-peasy.

I filed this one:
https://issues.dlang.org/show_bug.cgi?id=12625
implicit slicing of RValue static array should be illegal

While I do (kinda) agree we can't deprecate static array to 
dynamic array implicit conversion, THIS is one case we should 
ban. It's *never* correct. Always a bug.


More information about the Digitalmars-d-learn mailing list