On Thursday, 24 June 2021 at 14:06:11 UTC, seany wrote:
void f() {
a[] * rd;
// DO SOME WORK HERE ....
this.dataSet = & rd_flattened;
rd = cast (a [] *) dataSet;
write("length of rd is : "); writeln((*rd).length); // <---
this works..
// do some work on rd
this.dataSet = rd;
rd = cast (field.rawData [] *) dataSet;
write("length of rd for a second time is : ");
writeln((*rd).length); // <--- this ALSO works..
}
Now outside `f`, in the same class, i call :
void f2() {
f();
a[] *aa ;
aa = cast (a [] *) this.dataSet; // recall dataset is
public global
// if i print the address of this.dataSet here, this is the
same as inside f()
write("after calling f, count is: ");
writeln((*aa).length); readln();
// here the situation completely blows up . the length is
wrong.
}
What is causing this issue ?
Your variable `a[] rd_flattened;` is a local variable to function
`f()` allocated on the stack. Stack memory expires as soon as you
return from the function. What `f2()` accesses through your
global variable is a dangling pointer, a pointer to the expired
stackframe of `f()`, which is why the `.length` is garbage.