Given a struct such as this:
struct a {
int b;
int c;
my_t d[];
}
What do I have to pass to malloc
to allocate enough memory for a struct a
where d
has n
elements?
struct a *var = malloc(sizeof(*var) + n*sizeof(var->d[0]))
Using the variables for sizeof
will ensure the size is updated if the types change. Otherwise, if you change the type of d
or var
you risk introducing silent and potentially difficult-to-find runtime issues by not allocating enough memory if you forget to update any of the corresponding allocations.
You can use for instance: sizeof(struct a) + sizeof(my_t [n])
.
typedef int my_t;
struct a {
int b;
int c;
my_t d[];
};
int n = 3;
main(){
printf("%zu %zu\n", sizeof(struct a), sizeof(my_t [n]));
}
Result: 8 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With