Last active
March 23, 2021 20:28
-
-
Save williamcroberts/0006f4990e19f9a47da897e9aadfc83c to your computer and use it in GitHub Desktop.
Example of Bounds Checking At Compile Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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]