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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With