Skip to content

Instantly share code, notes, and snippets.

@williamcroberts
Last active March 23, 2021 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamcroberts/0006f4990e19f9a47da897e9aadfc83c to your computer and use it in GitHub Desktop.
Save williamcroberts/0006f4990e19f9a47da897e9aadfc83c to your computer and use it in GitHub Desktop.
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;
}
@williamcroberts
Copy link
Author

Compile with clang:

clang -Wall -Werror -Wextra -o go a.c

a.c:28:5: error: array index 45 is past the end of the array (which contains 32 elements) [-Werror,-Warray-bounds]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment