alloca is slow and dangerous

Patrick Schluter Patrick.Schluter at bbox.fr
Fri Jan 1 17:48:22 UTC 2021


On Friday, 1 January 2021 at 15:19:07 UTC, IGotD- wrote:
> On Friday, 1 January 2021 at 14:48:11 UTC, welkam wrote:
>> Over the years I saw several people asking why D doesn't have 
>> alloca. I just want to share a video where it states that 
>> alloca is slower than static array so we have one more 
>> arguments against it.
>> https://youtu.be/FY9SbqTO5GQ?t=468
>>
>> In summary alloca is:
>> 1. Hard to implement
>
> Why is it hard to implement?
>
>> 2. security problem
>
> Not entirely true. You need to check so that the amount 
> elements is within reasonable limits. You can have stack 
> overflows but most operating systems have guard pages detecting 
> such cases. In kernels it might not be the case but in kernels 
> you need pay attention more than in user space programs. Keep 
> in mind static arrays on the stack are prone to overflows just 
> as much as a VLA.

I think it is even worse than for VLA, because for the VLA you 
will have used a computed length depending on the parameters. So 
a real size. With static arrays, one will generally use a "worst 
case" size which value is much more prone to errors than the real 
length required.
Anecdote: recent gcc versions (since version 7) have for each 
version better and better heuristic to check the potential size 
of a buffers with string combination functions (sprintf, strcpy, 
strcat etc.). The number of potential worst case buffer overflows 
in legacy code is staggering.

>
> In D static arrays have an additional problem and that is that 
> D will initialize the array by default. For stability this is 
> great but performance this takes more time. VLA can be a better 
> option here as you initialize exactly the amount elements you 
> need.

yes

>
>> 3. slower than static array on the stack
>
> The reason was strangely a lot of code for just allocating on 
> the stack. He said he wasn't even using -O2 optimization and 
> with -O2 it would be smaller. In general it shouldn't be that 
> bad.

afaik VLA get in the way of clever frame pointer optimisations. 
Local variables and parameters will have to be accessed with 
slightly more costly code than if the code knows at compile time 
exactly where they are. Better optimizers and code generation can 
alleviate it in a lot of cases.

>
>
> The fear of alloca in my opinion is exaggerated.
>
> Doesn't D implement alloca for those who want it?
> https://dlang.org/phobos/rt_alloca.html

While I'm neither afraid nor sceptical towards VLA/alloca, I have 
to say after 10 years of use that there are really very few cases 
where it was really a substantial improvement. It often spared a 
malloc/free pair but more often than expected added memory 
copies. YMMV.


More information about the Digitalmars-d mailing list