Returning variable-sized stack data

IchorDev zxinsworld at gmail.com
Thu Jul 18 05:25:43 UTC 2024


On Wednesday, 17 July 2024 at 10:56:28 UTC, IchorDev wrote:
> This example works with dmd >= 2.084.1, but fails with ldc2/old 
> dmd for some reason:

OK I fixed it. It was the pesky slice copy that I forgot always 
breaks with overlapping slices. This updated example works with 
dmd >= 2.075.1 (earlier versions fail to compile because of what 
I must assume is a bug in `write`), and it also works with recent 
versions of LDC2:
```d
import std.typecons;
struct A{ int a,b,c,d,e,f,g; }
struct B{ int a,b,c; }
ubyte[] myFn(int n){
	auto nSqr = n * n;
	import core.stdc.stdlib: alloca;
	if(nSqr == 0){
		auto __returnPtr = alloca(A.sizeof);
		*cast(A*)__returnPtr = A(nSqr+1,2,3,4,5,6,7);
		return (cast(ubyte*)__returnPtr)[0..A.sizeof];
	}else{
		auto __returnPtr = alloca(B.sizeof);
		*cast(B*)__returnPtr = B(nSqr,2,7);
		return (cast(ubyte*)__returnPtr)[0..B.sizeof];
	}
}
void main(){
	int n = 0; //<—— can be any number
	ubyte[] myMem;
	{
		ubyte[] __returnMemory = myFn(n);
		import core.stdc.stdlib: alloca;
		myMem = 
(cast(ubyte*)alloca(__returnMemory.length))[0..__returnMemory.length];
		foreach(i; 0..myMem.length){
			myMem[i] = __returnMemory[i];
		}
	}
	import std.stdio;
	writeln(cast(int[])myMem);
}
```
For some reason casting back to `void[]` after the copy causes 
problems with the output.


More information about the dip.ideas mailing list