3 ms·
In pure C, there is no stack abstraction. Technically speaking, the stack is an extremely common implementation detail shared by almost all C runtimes. There's
by shadowgovt 5y ago
In pure C, there is no stack abstraction. Technically speaking, the stack is an extremely common implementation detail shared by almost all C runtimes.
There's no real way to answer this question at that layer of abstraction; the minute you add any library calls that deal with a stack at all (such as alloca), we're no longer talking about pure C.
- cryptonector 5y agoCorrect. Note that alloca() can be an alias for malloc() in stackless Cs. If the stack assumption is invalid, then a checker will not trip over a guard page, and it will at best trip over memory over-commit (which may still be desirable). If the guard page assumption is invalid, then a checker will cause failure just as surely as not checking (provided you intended to use the whole allocation anyways), and either way the failure will be undefined, therefore this is still portable C!
- chrisseaton 5y agoI was going to reply that alloca is a standard function, but then I checked and it's actually not is it!
- cryptonector 5y agoHowever VLAs are in C99 and up. They're rather similar to alloca() in that whatever mechanism you'd use to implement alloca() (automatic stack allocation, or heap allocation), you'd also use to implement VLAs.
- wahern 5y agoExcept alloca'd space is only dropped at the end of a function. VLAs are dropped at the end of a block. This makes a huge difference in loops as alloca can quickly exhaust the stack.
- cryptonector 5y agoNo real difference: for (size_t i = 1; i < WHATEVER; i <<= 1) { char vla[i]; vla[0] = 0; vla[i - 1] = 0; ... } that is, you can still exhaust your stack trivially with VLAs. Sure, the two things have a different "API", but as far as allocating arbitrary amounts of memory goes, they both let you do it.
- wahern 5y agoI'm not sure what your point is. You could replace the VLA with malloc in that example and exhaust your entire VM space. In the rare cases where VLAs might prove useful, e.g. a vector math library (IIRC, a major reason for VLAs was to help FORTRAN programmers transition to C), this difference absolutely does matter in reality.
- cryptonector 5y agoMaybe I missed the point of your comment. Mine is that the scoping difference between VLAs and alloca() isn't relevant to the question at hand of how to protect against memory corruption due to large stack allocations.
- steveklabnik 5y agoNotably, C11 moved alloca to an optional feature, not a required one.