Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a struct with flexible array member

Given

struct Foo {
    uint32_t a;
    uint32_t b[];
};

What is sizeof(Foo)? Is it implementation-defined or undefined behaviour? Does the answer differ for C vs C++?

like image 656
Timmmm Avatar asked Jul 19 '17 14:07

Timmmm


People also ask

How do you determine the size of a struct?

In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.

How do you determine the size of an array of structures?

foo=sizeof(para)/sizeof(para[0]);

What is the size of a struct?

A struct always gets its size adjusted to be n times the member with the highest alignment requirement. If you have an 8-byte double in the struct, then the struct must be n*8 bytes large, so your first example will need four bytes of padding.

What is flexible array member in C?

Flexible array members are a special type of array in which the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure.


1 Answers

The compiler will ignore the flexible array member as it were not there.

C11-§6.7.2.1 (p18)

[...] 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 [...].

AFAIK, flexible array member is not the part of C++ standard till c++14. But, GNU support it as an extension. Behaviour will be similar for both C and C++.

like image 132
haccks Avatar answered Sep 28 '22 01:09

haccks