3 ms·
btw C can already do this with VMTs: #define ARR_LEN(a) (sizeof (a) / sizeof *(a)) int a[5] = { 0, 1, 2, 3, 4}; int (*p)[ARR_LEN(a)] = &a; ARR
by camel-cdr 4y ago
btw C can already do this with VMTs:
#define ARR_LEN(a) (sizeof (a) / sizeof *(a))
int a[5] = { 0, 1, 2, 3, 4};
int (*p)[ARR_LEN(a)] = &a;
ARR_LEN(*p) // 5
- ryao 4y agoWhat does VMT mean? Virtual Method Table? When was this introduced to C? It looks like it was either in C89 or earlier according to both GCC and Clang. #define ARR_LEN(a) (sizeof (a) / sizeof (a)) int main(void) { int a[5] = {0, 1, 2, 3, 4}; int (*p)[ARR_LEN(a)] = &a; (*p)[6] = 1; return ARR_LEN(*p); // 5 } I had no idea this was possible in C. It is unfortunate that GCC seems to ignore this information. Clang on the other hand uses it.
- camel-cdr 4y ago> What does VMT mean? Variable modified types, they were introduces with VLAs (variable length arrays) in c99. C11 made both optional, and C2x mandates only VMTs.
- camel-cdr 4y agoAbout gcc ignoring it: gcc doesn't check array bounds at all, even `int x[2]; x[9] = 1;` doesn't produce a warning.
- ryao 4y agoOddly, it does catch it for the static example posted by someone else, but that is the only place where it catches it.
- uecker 4y agoYou need to use UBSan, then you get the bounds checking in GCC. I added this in 2015. https://godbolt.org/z/8ncEK3K5b https://godbolt.org/z/8ncEK3K5b
- uecker 4y agoIf you add warnings, it will also tell you that the ARR_LEN macro is wrong...