|
|
Subscribe / Log in / New account

C considered dangerous: VLAs

C considered dangerous: VLAs

Posted Sep 13, 2018 11:53 UTC (Thu) by nix (subscriber, #2304)
In reply to: C considered dangerous: VLAs by DHR
Parent article: C considered dangerous

Complaining that VLAs are expensive seems wrong. If you don't need a dynamically-sized array, why are you using a VLA? If you do need one, the only alternative is heap allocation, and that is more expensive and error-prone than stack allocation.
Quite. But of course the problem with both alloca() and VLAs is the same as the problem with automatic variables: error handling. If you run out of stack space, there is nothing you can do: it's game over. In a language without exceptions, there aren't even any edges control flow could propagate down, and no way to get the error out. Meanwhile, malloc() has always been able to return NULL (though, again, since nobody other than sqlite tests these failure cases systematically, it is questionable whether this is terribly useful).


to post comments

C considered dangerous: VLAs

Posted Sep 13, 2018 13:06 UTC (Thu) by excors (subscriber, #95769) [Link] (1 responses)

The lack of error handling means it's only safe to use VLAs (or alloca) if you know a static upper bound on the size of the array, and it's small enough that you're confident it's never going to overflow the stack. But if you know an upper bound, why not just always allocate that much? Overallocating seems unlikely to have any performance impact in typical cases. And if the stack is too small for your constant-sized array, you'll find out immediately and can fix it, rather than the failure being dependent on (possibly-attacker-controlled) variables, so it makes the behaviour more predictable and easier to debug.

C considered dangerous: VLAs

Posted Sep 13, 2018 18:51 UTC (Thu) by nix (subscriber, #2304) [Link]

Good points. VLAs might still be useful if your maximum depends on some other variable, *and* you are confident you have enough space, but frankly by this point either you're in a hot inner loop or you should be using malloc() anyway.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds