SKi
SKi

Reputation: 8466

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?

Upvotes: 18

Views: 5684

Answers (2)

ShinTakezou
ShinTakezou

Reputation: 9671

Your example do work since C has not arrays that dynamically become bigger when you add elements. So size of *msg is sizeof u32 + paddings, if any, but it won't count for list member, which you have to consider by yourself when you "alloc" the buffer and when you want to know the actual size of that "object", as you did.

Upvotes: 1

Graham Borland
Graham Borland

Reputation: 60681

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.

Upvotes: 19

Related Questions