I'm going through a surge of interest in C99's variably-modified type system. This question was inspired by this one.
Checking the code from this question, I discovered something interesting. Consider this code:
int myFunc(int, int, int, int[][100]);
int myFunc(int a, int b, int c, int d[][200]) {
/* Some code here... */
}
This obviously won't (and does not) compile. However, this code:
int myFunc(int, int, int, int[][100]);
int myFunc(int a, int b, int c, int d[][c]) {
/* Some code here... */
}
compiles without even a warning (on gcc).
That seems to imply that a variably-modified array type is compatible with any non-variably-modified array type!
But that's not all. You'd expect a variably-modified type to at least bother with which variable is used to set its size. But it doesn't seem to do so!
int myFunc(int, int b, int, int[][b]);
int myFunc(int a, int b, int c, int d[][c]) {
return 0;
}
Also compiles without any error.
So, my question is: is this correct standardized behaviour?
Also, if a variably-modified array type would really be compatible with any array that has the same dimensions, wouldn't this mean nasty security problems? For example, consider the following code:
int myFunc(int a, int b, int c, int d[][c]) {
printf("%d\n", sizeof(*d) / sizeof((*d)[0]));
return 0;
}
int main(){
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
myFunc(0, 0, 100, &arr);
return 0;
}
Compiles and outputs 100, no errors or warnings, nothing. As I see it, that means easy out-of-bounds array write even if you are strictly checking the size of your array via sizeof
, not doing a single cast and even have all warnings turned on! Or am I missing something?