Question about arrays

Etienne etcimon at gmail.com
Wed Jan 22 10:14:04 PST 2014


I'm trying to pinpoint the difference in array handling of stack arrays 
vs heap arrays. More precisely, trying to understand how to use arrays 
with malloc data. Here's a sample of the experiment:

------
import std.stdio;
import std.typecons;
auto callit(){

	ubyte[50] heapSrc1 = new ubyte[50];
	ubyte[50] stackSrc1;
	ubyte[] heapDst1 = new ubyte[50];
	ubyte[] heapDst2 = new ubyte[50];
	ubyte[50] stackDst1;
	ubyte[50] stackDst2;
	stackSrc1[5] = 4;
	heapSrc1[0] = 10;
	heapDst1 = heapSrc1[0..50];
	heapDst2 = stackSrc1[0..50];
	stackDst1 = heapSrc1[0..50];
	stackDst2 = stackSrc1[0..50];
	heapSrc1[5] = 10;
	heapDst1[2] = 5;heapDst2[2] = 5;stackSrc1[3] = 10;
	return tuple(heapDst1,heapDst2,stackDst1,stackDst2);
}

void main()
{
	auto a = callit();
	a[0][1] = 5;
	foreach (id, el ; a)
		writeln(id, " => ", el);
}
-------

I found that copying on the heap has to be explicitly specified, while 
copying to the stack is forced:
Works: heap1[] = heap2[]; heap1[] = stack1[];
Doesn't: heap1 = stack1[]; heap1 = heap2[];

Which brings me to the point: if I understand D's return syntax 
correctly, the variables would be copied on the stack in a new tuple. 
What I don't understand is why the return call of callit() doesn't copy 
the heap data on the stack as expected. Even if it copies just the 
pointer to the data (which justified deleting heapDst2's data because it 
was on stack), why does the data at heapDst1 and heapSrc1 get collected 
by the GC and point to gibberish when callit() returns?

Thanks


More information about the Digitalmars-d mailing list