3 ms·
Nobody should use alloca. If you must allocate a buffer on the stack, use a VLA, which is standardized, has proper scope-bound lifetimes, and a type that rememb
by uecker 2mo ago
Nobody should use alloca. If you must allocate a buffer on the stack, use a VLA, which is standardized, has proper scope-bound lifetimes, and a type that remembers the exact size. Yes, I know MSVC does not upport it. Don't use this compiler. (where credit is due: MSVC had stack probing a lot ealier than GCC and clang, and clang was very late).
With gcc, you get stack probing with -fstack-clash-protection, which is similar to _chkstk but GCC inlines the stack probes.
VLA got a bad name because of stack clash attacks, but without stack clash protection these attacks can appear also without VLAs (and the first such attacks actually exploited fixed-size arrays), and if you activate this protection there is IMHO not much reason to avoid VLAs.
If you need a small variably-sized buffers, VLAs are almost always superior to any alternative. alloca is worse in every way (see above), a regular array with worst-case bound increases stack use relative to a VLA and does not encode the correct dynamic size which makes bounds checking weaker, and moving the buffer to the heap is slower and complicates the code.
If you can not properly account for the sizes of the things you put on your stack and worry about VLAs exceeding the limit (but again, regular arrays with worst-case size increase stack usage compared to VLAs), on GCC you can use -Wvla-larger-than to make sure the size of each VLA stays bounded.
- rurban 2mo agoOn the contrary, nobody should use VLA, rather use alloca, if small enough. VLA is very new, compiler horror, poorly supported and on the chopping block. alloca is supported for decades already
- uecker 2mo agoThere are certainly not on the chopping block and were standardized in C99. alloca will certainly never be standardized.
- rurban 2mo agoAccording to the WG21 and WG14 discussions, VLA is definitely questioned
- uecker 2mo agoThere is definitely random hate against this feature from some sides. But no good arguments as far as I can see.
- rurban 2mo agoWell, you can add me to the haters. A monster to implement
- uecker 2mo agoWhat is hard to implement about it? I implemented in my toy compiler without a major problem. x86_64 ABI for passing structures or C's initializers were harder to implement. Many other programming languages such as Ada have VLAs on the stack as well.
- spacechild1 2mo agoC11 made VLA optional again. C++ never standardized it in the first place.
- uecker 2mo agoAccording to people which were there, things were made optional in C11 because C99 was slowly adopted, not because there were any concerns with the feature.
- account42 2mo agoIf you can't put an relatively small upper bound on the allocation then it probably shouldn't be on the stack in the first place.
- uecker 2mo agoWhy is that?