Does a flexible array element increase the size of the structure?

I have the following code:

typedef struct { u32 count; u16 list[]; } message_t; ... message_t* msg = (message_t*)buffer; msg->count = 2; msg->list[0] = 123; msg->list[1] = 456; size_t total_size = sizeof(*msg) + sizeof(msg->list[0]) * msg->count; send_msg( msg, total_size ); 

The problem line is a line with sizeofs. I'm not sure if this is the right way to calculate the required space. Does sizeof(*msg) have anything about a list member?

I can check it with my compiler, but does each compiler work in this case?

+6
source share
2 answers

Here is what the standard says:

As a special case, the last element of the structure with more than one named element may have an incomplete array type; this is called a flexible array element. In most situations, the flexible array element is ignored. In particular, the size of the structure looks like this: the flexible element of the array was omitted , except that it may have more, which means that it will mean scrolling to the end than omission.

+9
source

Your example works because C does not have arrays that dynamically grow larger when elements are added. Thus, the size * msg is equal to sizeof u32 + paddings, if there is one, but it will not be taken into account for a member of the list, which you must take into account when you "allocate" the buffer and when you want to know the actual size of this "object", as and you.

+1
source

Source: https://habr.com/ru/post/892983/


All Articles