How to calculate the amount of memory needed for a variable length structure?

For such a structure:

struct a { int b; int c; my_t d[]; } 

What do I need to pass to malloc to allocate enough memory for struct a , where d has n elements?

+8
c sizeof malloc
source share
3 answers
 struct a *var = malloc(sizeof(*var) + n*sizeof(var->d[0])) 

Using variables for sizeof ensures that the size will be updated if the types are changed. Otherwise, if you change the type d or var , you run the risk of introducing silent and potentially hard-to-reach problems at run time without allocating enough memory if you forget to update any of the corresponding distributions.

+9
source share

You can use, for example: 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

+5
source share

That should be enough:

 sizeof(a) + n * sizeof(my_t) 
+4
source share

All Articles