Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

sizeof

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?

like image 279
fuz Avatar asked Nov 17 '12 21:11

fuz


2 Answers

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.

like image 198
Kevin Avatar answered Sep 20 '22 11:09

Kevin


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

like image 24
Pascal Cuoq Avatar answered Sep 16 '22 11:09

Pascal Cuoq