<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/107152>107152</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Does changing the order of members in the union affect the actual memory content of the union?
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
edumoot
</td>
</tr>
</table>
<pre>
The test case comes from #107144.
I have a question: in the context of C, would changing the order of elements in a union impact the memory content of the union?
In a union,
- the size of the union is determined by its largest member.
- all members share the same memory space.
Can we make a conclusion that the relative memory layout of the members doesn't change based on the order of definition?
```
clang -g -O3 -o 402_O3.out 402.c
(lldb) file 402_O3.out
(lldb) b 38
(lldb) r
[...]
(lldb) p global_union
(volatile U3) {
f0 = (f0 = -1, f1 = 8313)
f1 = -1
}
(lldb) mem read &global_union
0x555555558030: ff ff ff ff 79 20 00 00 00 00 00 00 00 00 00 00 ....y ..........
0x555555558040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
(lldb)
```
Now, we change the order of elements in the union while keeping the remaining at the same, and save it as 'test.c'.
```
union U3 {
signed f1 ;
struct S0 f0;
};
.
.
.
clang -g -O3 -o test_O3.out test.c
(lldb) file test_O3.out
(lldb) b 38
(lldb) r
[...]
lldb) p global_union
(volatile U3) {
f1 = -1
f0 = (f0 = -1, f1 = 0)
}
(lldb) mem read &global_union
0x555555558030: ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x555555558040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
```
The last wo bytes `79 20` changed to `00 00`
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0VU2TozYQ_TXypcuUEGDMgcPOuFyVS_aQ7HlLoAaUFZIjCXudX58SHx47eGZT-aAo2Wr1e2q1-tHcOdlqxJJkLyQ7bPjgO2NLFENvjN9URlzLXzsEj85DzR1CbXp00FjTA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