Re:Git's list of banned C functions
by ufo on Thursday March 04, 2021 @08:55PM
(#26351497)
We wouldn't need to go all the way to dependent types, which would guarantee at compile-time that array accesses are safe. Even if all the bounds checking happened at run-time it would still be tremendously helpful.
[ Parent
| on HN ]
Bounds checking can be done, and it doesn't need any special language features. Tcc does it, as do some of the sanitizers (present in gcc and clang).
Can you bounds check dynamically sized arrays? For example, a function that receives the size as a separate argument?
double f(double *xs, int n){
return xs[g()];
}Yes. In my hypothetical world where the C compiler makes use of the VLA declaration in the function arguments, it would certainly be possible for the compiler to insert automatic bounds checking in this case:
double f(xs, n)
double xs[n];
size_t n;
{
size_t _tmp0 = g(); /* temporary var created by compiler */
assert(_tmp0 < n); /* bounds check inserted by compiler */
return xs[_tmp0];
}
The key to making this possible is telling the compiler about the relationship between double* xs and size_t n; once the compiler has the knowledge that the type of xs is double [n] (array of double with first dimension n) it would be able to automatically insert dynamic bounds checks.> dynamically sized arrays
Yes. What you can't do is associate bounds information with some specific pointer to an array, but this will work, for instance:
int *x = malloc(2 * sizeof(int));
x[1]; //ok
x[2]; //runtime error