Returning dynamic array from the function

Simen Kjaeraas simen.kjaras at gmail.com
Wed Oct 17 12:21:48 PDT 2012


On 2012-10-17, 21:17, m0rph wrote:

> I tryed to learn how arrays works and found another strange thing:
>
> import std.stdio;
>
> int[] create()
> {
> 	int[5] a1 = [ 10, 20, 30, 40, 50 ];
> 	int[] b1 = a1;
> 	writeln("b1: ", b1);
> 	return b1;
> }
>
> void main()
> {
> 	int[] a2 = create();
> 	writeln("a2: ", a2);
> }
>
> Result of execution:
> b1: [10, 20, 30, 40, 50]
> a2: [-142625792, 32767, 4358059, 0, 5]
>
> Please explain what's wrong with this code? Why variable a2 contains  
> crap? Is this another dmd/druntime bug or I missed something?

b1 points to the exact same data as does a1. This data is stack-
allocated, and thus a2 points to an overwritten stack frame.

-- 
Simen


More information about the Digitalmars-d-learn mailing list