From 9e01ce1f3137f5d155689e8c419ff104e39da0c6 Mon Sep 17 00:00:00 2001 From: Jan Pechanec Date: Tue, 28 Jan 2025 21:06:20 +0100 Subject: [PATCH] Extending the example. --- src/flexible-array-member.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/flexible-array-member.c b/src/flexible-array-member.c index 4d5c9c2b..63ce69da 100644 --- a/src/flexible-array-member.c +++ b/src/flexible-array-member.c @@ -1,5 +1,6 @@ -#include +#include #include +#include struct item { int header; @@ -10,7 +11,11 @@ struct item { static struct item * allocate(size_t payload_len) { - /* offsetof(struct item, payload) might be better to use here. */ + /* + * offsetof(struct item, payload) might be better to use here as + * otherwise we might allocate more than necessary due to padding that + * could otherwise be used for the flexible array member. + */ struct item *p = malloc(sizeof (struct item) + payload_len * sizeof (p->payload[0])); if (p == NULL) @@ -29,8 +34,17 @@ main(void) { struct item *p = allocate(30); - for (size_t i = 0; i < p->len; ++i) + /* + * This is always the size without the flexible array member. Note that + * padding might be inserted by the compiler. + */ + printf("sizeof (item): %zu\n", sizeof (*p)); + printf("offsetof (item, payload): %zu\n", + offsetof(struct item, payload)); + + for (size_t i = 0; i < p->len; ++i) { printf("%zu: %c\n", i, p->payload[i]); + } free(p); }