Re: How to I get pointer to an Array and cast to a void * and back ?

2021-06-24 Thread Dennis via Digitalmars-d-learn

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.




How to I get pointer to an Array and cast to a void * and back ?

2021-06-24 Thread seany via Digitalmars-d-learn

I have a struct :

struct a {
   int i;
   // some more stuff ...
}

In a Class, I define public global `void * dataSet; `

In a function `f`, of the same class:  i call :

void f() {
a[] rd_flattened;   
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.

}


I need some help here. Sorry, can't post code. It is proprietary.

What is causing this issue ?

thank you.