back

by uecker·2y ago·view on hn ↗
You could pass a pointer to the array instead of letting it decay:

int get(int n, char (*buffer)[n]) { return buffer[10]; }

int main() { char buffer[10]; get(10, &buffer); }

Then a run-time bounds checker or a model checker can find the bug: https://godbolt.org/z/a4ExKMn1s

1 comments
If you "just" want bounds checking, then you don't need a pointer to array. GCC is able to detect the out-of-bound even in this case:

  int get(int n, char buf[n])
  {
    return buf[10];
  }
It's if you want to use sizeof that you need a pointer to array. But if you have n, why would you need to query the size of your array?
A possible answer is that one could modify n inside the function body, which means that the length is lost. But honestly, one could just use const to avoid this. Though, pointers to VLAs are really useful and convenient when allocating dynamic arrays, especially multidimensional.
GCC only works in the first case anyway: https://godbolt.org/z/jo57r1MW4 One could add in the other too, but language semantics currently do not allow this.

Changing the n later has no impact on the size of the arrays later and the compiler is perfectly able to remember the original size.