if (n > MAX){
return;
}
Would not help?* the code is bigger, and people say is meaningfully slower
* super easy to accidentally blow the stack - in kernel land that is probably going to end in a panic
* using vLAs used to disable stack canaries for those frames, not sure if it still does
For a lot of cases where you are truly going to need variable length you’re unlikely to be penalised heavily by a heap allocation due to the relative cost of the operations.
really ? there's a difference but unless you keep allocating in a hot-loop this should hardly ever have observable costs : https://gcc.godbolt.org/z/SN9Ois
A really nice use for a VLA would be in the middle of a struct. You could make something like a PNG image file chunk as a struct, with the CRC at the end coming after the VLA. You get a struct of the correct size with the right fields, despite one part of the struct being of variable size.
For example, a parameter n is passed to a function, and then a struct is defined based on n.
struct {
uint32_t header;
uint32_t array[n];
uint32_t footer;
}foo;
The function fills in the struct. Maybe it then sends the struct via a packet-oriented protocol, perhaps over a datagram socket, so the length is transmitted implicitly in the packet size.https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
There is no problem cleaning the stack because the compiler has numerous ways to do that. One way is to keep a copy of the original n, as passed to the function. Another way is to save the original stack pointer.
Making this work is not much harder than supporting the alloca function.
If you prefer, it's an Ethernet packet, with a CRC16 on the end. It is outbound.
The send() and write() functions are happy to accept a void pointer.
Of course whether any of this matters will depend on the specifics of the matter, kernel code being the most conservative by necessity.
uint8_t is effective protection, given the normal assumption of a stack with 4096 to 16384 bytes of space and a call stack that isn't insane.
If you wish to make a formal proof of correctness, feel free to make worst-case assumptions.
Same issue, you just need larger values. In both cases you need a guard.
I guess if you have a really large n, like more than a few pages worth, then certain values of m[i] might wind up in some other page allocation where it shouldn't.... I seem to recall a vulnerability like this a year or two ago. (Normally a stack can grow on a page fault by hitting a guard page, but if the n above is absurdly large...)