Skip to content

Commit

Permalink
Extending the example.
Browse files Browse the repository at this point in the history
  • Loading branch information
janpgit committed Jan 28, 2025
1 parent f0c50bd commit 9e01ce1
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/flexible-array-member.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

struct item {
int header;
Expand All @@ -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)
Expand All @@ -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);
}

0 comments on commit 9e01ce1

Please sign in to comment.