static array internal & dangling reference

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 14 09:15:43 PST 2016


On 11/14/16 12:53 AM, Picaud Vincent wrote:
> On Sunday, 13 November 2016 at 23:39:37 UTC, Steven Schveighoffer wrote:
>
>> Note that he is declaring an int[10] inside the function and then
>> returning it. The compiler must see that the int[10] will be returned,
>> and so it reuses the pre-allocated buffer for returning as the same
>> address to avoid copying.
>>
>> I would guess it's probably fine, with no dangling reference.
>
> Thank you for your comment.
>
> On my side there is still something mysterious. I one case:
>
> int[] f()
> {
>   int[10] sa;
>   foreach(int i, ref sa_i;sa){
>     sa_i=i;
>   }
>   int[] sb=sa;
>   return sb;
> }
>
> void f_test()
> {
>   auto sb=f();
>   sb[2]=100;     // Valgrind ok
> }
>
> Valgrind does not complain.

What has happened is that the stack allocated for f() (and since 
released) is still referenced by sb[]. In a weird way, since you haven't 
called any other functions, that data is still "valid"!

I'm not sure what valgrind uses to determine what data is uninitialized 
or allocated, but in a very real sense, this code is deterministic, and 
will always result in the same result. Is it good practice? No. It's 
very fragile, and would break as soon as you called another function or 
reallocated that stack space (as your second example shows).

I think valgrind is either trying not to be very assuming on how your 
code works, or it simply hasn't seen any real undefined behavior based 
on how you are reading/writing memory. Remember, valgrind has no idea 
what language you are using, or what compiler optimization shortcuts 
have been employed.

-Steve


More information about the Digitalmars-d-learn mailing list