2 ms·
Just use array properly and you get run-time bounds checking: https://godbolt.org/z/4a45xq5hr https://godbolt.org/z/4a45xq5hr (yes, a bit more compiler support
by uecker 3y ago
Just use array properly and you get run-time bounds checking:
https://godbolt.org/z/4a45xq5hr https://godbolt.org/z/4a45xq5hr
(yes, a bit more compiler support is necessary to make this safe. I posted a patch to GCC, let's see)
- lelanthran 3y agoTIL ... I never knew that you got runtime bounds-checking with VLAs. Do you have a link that explains this snippet in more detail? Why/how does it work? It doesn't appear to work with non-VLAs though.
- uecker 3y agoIt works because the type (char (buf)[n]) knows the dynamic size 'n'. So the compiler can simply add the bounds check to an array access (buf)[i] if instructed to do so. If you replace the sizes with constants it also works: https://godbolt.org/z/sKPW6zT87 https://godbolt.org/z/sKPW6zT87 The safety story is not complete though: If you pass the wrong size to 'foo' this is not detected (this is easy to add to compilers and I submitted a patch to GCC which would do this): https://godbolt.org/z/T8844e1z8 https://godbolt.org/z/T8844e1z8 (ASAN still catches the problem in this case, but ASAN does not work consistently and has a high run-time overhead.)