c++ - Structure initialization corruption
- Piotr Grochowski (27/27) Apr 04 2023 ```cpp
```cpp struct shortwrap{short s; inline shortwrap(short q){s=q;}}; struct pkf{ long a; float b; shortwrap c[4]; double d; }; #include <stdio.h> int main(){ pkf t={0x33333333,0.1f,{4,{6,},8,9,},1./7}; for(int i=0;i<sizeof t;i++){printf("%02x ",((unsigned char*)&t)[i]);} } ``` Here a structure is being initialized. The expected bytes are the following: `33 33 33 33 cd cc cc 3d 04 00 06 00 08 00 09 00 92 24 49 92 24 49 c2 3f` However, the items initialized by short initializing shortwrap array overwrite the start of pkf structure instead of the proper position. `04 00 33 33 08 00 09 00 00 00 06 00 00 00 00 00 92 24 49 92 24 49 c2 3f` Notice that the 6, which is initialized directly from the shortwrap structure entries is initialized in the correct location, but 4, 8, and 9 end up corrupting structure start.
Apr 04 2023