cstructsizeofflexible-array-member

Does a flexible array member increase sizeof a struct?


I have the following kind of 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 ); 

Problematic line is the line with sizeofs. I am not sure is that correct way to count needed space. Does sizeof(*msg) contains already something about the list member?

I can test it with my compiler, but does every compiler work similary in this case?


Solution

  • Here's what the standard says:

    As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.