static array internal & dangling reference

Andrew via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 12 04:16:02 PST 2016


On Saturday, 12 November 2016 at 11:03:31 UTC, Mike Parker wrote:
>>[...]
>
> You *have* created a dangling pointer. It's just that for such 
> a simple little program, the part of the stack where the 
> original array was allocated isn't stomped at the point where 
> you access it after the function call. The same sort of program 
> will also work in C, where it's not uncommon for functions to 
> return string literals that are immediately printed to stdout 
> or a log file.
>
> One difference from C in this case is that it's still possible 
> to make things work even after the stack has been stomped and 
> the memory is no longer valid simply by increasing the length 
> of the returned slice: sb ~= 0, or perhaps sb.length+=n. This 
> will cause an allocation and sb will then own the memory block 
> to which it points.
>
> Bear in mind that static arrays are implicitly sliced when 
> passed to or returned from a function anywhere a dynamic array 
> is expected. If you modify f() to look like this:
>
> int[] f()
> {
>   int[10] sa;
>   foreach(int i, ref sa_i;sa){
>     sa_i=i;
>   }
>   return sa;
> }
>

I thought that if you changed the function signature to int[10] 
f() to return a static array, this should be returned by value, 
and so should be safe to use, but it seems that this too points 
to the same memory.

To make it safe, should I be using:

auto sb = f().dup;

Thanks

Andrew


More information about the Digitalmars-d-learn mailing list