4 ms·
However 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 h
by cryptonector 5y ago
However 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.