Skip to content

Instantly share code, notes, and snippets.

@williamcroberts

williamcroberts/example.c

Last active Mar 23, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@williamcroberts williamcroberts commented Mar 23, 2021

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