<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/62929>62929</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Clang: size of struct with FAM with initialization
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          uecker
      </td>
    </tr>
</table>

<pre>
    GCC has an extension for statically initialization of structs with a flexible-array member which clang also supports. Consider this example:

struct foo { int a; char b; char c[]; } x = { .c = { 1, 2, 3, 4 }; };
https://godbolt.org/z/jKxbzEvdo

GCC would allocate 12 bytes for this on x86_64 which is the same as the size of a struct with replacement array. This also corresponds to what programmers typically allocate on the heap for such structs using the size given by sizeof(struct foo) + n * sizeof(char).  

Starting with clang 15 clang only allocates 9 bytes for such struct. There are three potential concerns with this:
1. it is not the same as what the GCC extension does
2. it is not what the common rule for computing the size yields, so when using memcpy with this rule on such a struct this may cause an out-of-bounds access
3. it is not compatible with the rule in the C standard that says that a struct with FAM behaves as if replaced with the largest array that would not make the struct larger than the object. But the largest such array in the example above would hold only three elements (size 8), not four (size 12).

GCC bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109956
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJxcVM1yqzgTfRp50xUXFuCYBYvY-fwtpmY1s7_ViAZ0r5Ao_cR2nn6qgdhONnJjSd2nzzktDEH3lqgW5VGU7xtMcXC-TqT-kN80rr3V_z-dYMAAaIGukWzQzkLnPISIUSs05gba6qjR6E-MvOs6CNEnFQNcdBwAoTN01Y2hF_QebzDS2JCHy6DVAMqg7QFNcBDSNDkfwxZOzgbdkoc46AB0xXEyJPI3kb2LbF2XGtA5B-L1CNpGQJEfQQ3ooblHaumNv8XrO1xB5O_zha26hzshTyB5yXkp-OR6QeTHpdwQ4xQYgjwLee5d2zgTt873Qp4_hTz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