Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a flexible array member increase sizeof a struct?

Tags:

c

struct

sizeof

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?

like image 753
SKi Avatar asked Jul 18 '11 11:07

SKi


2 Answers

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.

like image 110
Graham Borland Avatar answered Oct 19 '22 11:10

Graham Borland


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.

like image 37
ShinTakezou Avatar answered Oct 19 '22 09:10

ShinTakezou