dynamically allocating on the stack
Timon Gehr
timon.gehr at gmx.ch
Sat Apr 21 10:47:47 UTC 2018
On 21.04.2018 12:08, Giles Bathgate wrote:
> On Saturday, 21 April 2018 at 07:57:41 UTC, Uknown wrote:
>> The language itself doesn't have something, but you could use `alloca`
>
> I don't know if this little template function makes life easier:
>
> ------
> pragma(inline, true)
> ref T push(T)(size_t len)
> {
> import core.stdc.stdlib, core.stdc.stdio;
>
> return *cast(T*)alloca(T.sizeof * len);
> }
>
>
> void doSomething(size_t len)
> {
> auto stackBuffer = push!char(len+1);
> stackBuffer[0] = 'H';
> stackBuffer[1] = '\0';
> printf("%.*s", stackBuffer.ptr);
> }
>
> void main()
> {
> doSomething(2);
> }
> ------
>
>
That does not work (you are returning a dangling reference into the
stack of the function that is returning). You could do this:
import core.stdc.stdlib, core.stdc.stdio;
auto push(T,alias len)(T[] mem=(cast(T*)alloca(T.sizeof*len))[0..len]){
return mem; // (uninitialized!)
}
void doSomething(size_t len){
char[] stackBuffer=push!(char,len);
stackBuffer[0] = 'H';
stackBuffer[1] = '\0';
printf("%s", stackBuffer.ptr);
}
void main(){
doSomething(2);
}
More information about the Digitalmars-d-learn
mailing list