Possible bug in associative array implementation (and/or @safe checking)
Aaron D. Trout
atrout at chatham.edu
Thu Aug 16 18:32:11 UTC 2018
[...]
On Thursday, 16 August 2018 at 17:20:23 UTC, Steven Schveighoffer
wrote:
>
> Yes, this is the effect I would expect.
>
> D has traditionally simply allowed slicing stack data without
> question (even in @safe code), but that will change when
> dip1000 is fully realized. It will be allowed, but only when
> assigning to scope variables.
>
> -Steve
Thanks for the quick and knowledgeable reply! I think I
understand what's going on, but I'm surprised it is allowed in
@safe code since the compiler doesn't allow the following, even
in non- at safe code:
int[] badSlice()
{
int[2] buffer;
return buffer[];
}
I guess the compiler just isn't (yet!) able to catch that the
associative array is storing a slice of expired stack. I'm
surprised that the built-in AA implementation *allows* using
slices as keys in @safe code without copying the underlying data
to the heap first. This is clearly dangerous, but perhaps
heap-copying slices defensively would result in an unacceptable
performance hit.
This issue came up while trying to eliminate unnecessary
allocation in my code. In my case, I could set a maximum key
length at compile time and switch my key type to a struct
wrapping a static array buffer.
In hindsight, it was silly for me to think I could eliminate
separately allocating the keys when the key type was a variable
length array, since the AA must store the keys. That said, a
suitable admonition from the compiler here would have been very
educational. I look forward to seeing the full inclusion of
DIP1000!
More information about the Digitalmars-d-learn
mailing list