On Sunday, 22 April 2018 at 06:00:15 UTC, WhatMeForget wrote:
foreach(i, elem; a) { int[] temp = new int[](5); ...... a[i] = &temp; }
You're taking the address of a local variable and persisting it beyond the variable's scope. This is not safe in general; compilers regularly reuse spaces on the stack. DMD specifically tends to do this reliably with foreach loop bodies.
You see the same thing in C: #include <stdio.h> int main(int argc, char** argv) { int* p[2]; for (int i = 0; i < 2; i++) { int f = i; p[i] = &f; } printf("p[0] = %x, *p[0] = %d\n", p[0], *p[0]); printf("p[1] = %x, *p[1] = %d\n", p[1], *p[1]); return 0; } Which prints something like: p[0] = d9b69428, *p[0] = 1 p[1] = d9b69428, *p[1] = 1