Example of Bounds Checking At Compile Time
typedef union TPM2B_FOO TPM2B_FOO; | |
union TPM2B_FOO { | |
struct { | |
uint16_t size; | |
uint8_t data[32]; | |
}t; | |
TPM2B b; | |
}; | |
int main(int argc, char *argv[]) { | |
(void) argv; | |
TPM2B_FOO foo = { | |
// Nested initializers need another level | |
.t = { | |
.size = 3 | |
}, | |
}; | |
// This will cause error: array index 45 is past the end of the array (which contains 32 elements) | |
foo.t.data[45] = argc; | |
printf("foo.t.size: %u", foo.t.size); | |
// This will bypass compiler checks | |
foo.b.data[45] = argc; | |
printf("foo.b.size: %u", foo.b.size); | |
printf("foo.b.data[45]: %u", foo.b.data[45]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Compile with clang:
a.c:28:5: error: array index 45 is past the end of the array (which contains 32 elements) [-Werror,-Warray-bounds]