Struct inside a union
I came across the following c code.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint32_t size;
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
When I try to test it, I came across some weird behavior, I hope someone can help me figure out what's wrong with this definition. I did some search, but there were no similar problems.
Here is what I tried:
uint8_t test1 = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
int i = 0;
for(i = 0; i < sizeof(test1); i++)
{
packet.raw[i] = test1[i];
}
printf("packet.size_word[0]=0x%04xn", packet.size_word[0]);
printf("packet.size_word[1]=0x%04xn", packet.size_word[1]);
Output is
packet.size_word[0]=0x0605
packet.size_word[1]=0x0807
It completely missed 0x03 and 0x04.
When I use the following definition (remove "uint32_t size;"), it works fine.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
Here is the output:
packet.size_word[0]=0x0403
packet.size_word[1]=0x0605
Does anyone know why this is happening? I thought items in union always occupied same memory location.
Here is the link for the code.
The original Code is here.
--------------------------Update 11/25/2018---------------------------------
So I'm confident now it's the structure padding and it depends on the CPU architecture.
I tested on Arduino with Atmega328p (an 8-bit MCU), it works like a charm. There was no struct padding since the MCU process 1 byte each time.
However, the code is not portable at all as @selbie mentioned, when writing such code, we have to consider CPU architecture and environment. Simplest solution is not using it.
Further reading:
C – Structure Padding
Structure padding and packing
c struct unions packing
|
show 2 more comments
I came across the following c code.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint32_t size;
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
When I try to test it, I came across some weird behavior, I hope someone can help me figure out what's wrong with this definition. I did some search, but there were no similar problems.
Here is what I tried:
uint8_t test1 = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
int i = 0;
for(i = 0; i < sizeof(test1); i++)
{
packet.raw[i] = test1[i];
}
printf("packet.size_word[0]=0x%04xn", packet.size_word[0]);
printf("packet.size_word[1]=0x%04xn", packet.size_word[1]);
Output is
packet.size_word[0]=0x0605
packet.size_word[1]=0x0807
It completely missed 0x03 and 0x04.
When I use the following definition (remove "uint32_t size;"), it works fine.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
Here is the output:
packet.size_word[0]=0x0403
packet.size_word[1]=0x0605
Does anyone know why this is happening? I thought items in union always occupied same memory location.
Here is the link for the code.
The original Code is here.
--------------------------Update 11/25/2018---------------------------------
So I'm confident now it's the structure padding and it depends on the CPU architecture.
I tested on Arduino with Atmega328p (an 8-bit MCU), it works like a charm. There was no struct padding since the MCU process 1 byte each time.
However, the code is not portable at all as @selbie mentioned, when writing such code, we have to consider CPU architecture and environment. Simplest solution is not using it.
Further reading:
C – Structure Padding
Structure padding and packing
c struct unions packing
4
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
6
2 bytes of padding precede the second union to alignuint32_t sizeto a 4-byte boundary. You can see this with:printf("%zun", offsetof(union packet_t, size));
– Brett Hale
Nov 25 '18 at 5:47
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition ofunion packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.
– eapetcho
Nov 25 '18 at 5:49
1
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39
|
show 2 more comments
I came across the following c code.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint32_t size;
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
When I try to test it, I came across some weird behavior, I hope someone can help me figure out what's wrong with this definition. I did some search, but there were no similar problems.
Here is what I tried:
uint8_t test1 = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
int i = 0;
for(i = 0; i < sizeof(test1); i++)
{
packet.raw[i] = test1[i];
}
printf("packet.size_word[0]=0x%04xn", packet.size_word[0]);
printf("packet.size_word[1]=0x%04xn", packet.size_word[1]);
Output is
packet.size_word[0]=0x0605
packet.size_word[1]=0x0807
It completely missed 0x03 and 0x04.
When I use the following definition (remove "uint32_t size;"), it works fine.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
Here is the output:
packet.size_word[0]=0x0403
packet.size_word[1]=0x0605
Does anyone know why this is happening? I thought items in union always occupied same memory location.
Here is the link for the code.
The original Code is here.
--------------------------Update 11/25/2018---------------------------------
So I'm confident now it's the structure padding and it depends on the CPU architecture.
I tested on Arduino with Atmega328p (an 8-bit MCU), it works like a charm. There was no struct padding since the MCU process 1 byte each time.
However, the code is not portable at all as @selbie mentioned, when writing such code, we have to consider CPU architecture and environment. Simplest solution is not using it.
Further reading:
C – Structure Padding
Structure padding and packing
c struct unions packing
I came across the following c code.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint32_t size;
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
When I try to test it, I came across some weird behavior, I hope someone can help me figure out what's wrong with this definition. I did some search, but there were no similar problems.
Here is what I tried:
uint8_t test1 = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};
int i = 0;
for(i = 0; i < sizeof(test1); i++)
{
packet.raw[i] = test1[i];
}
printf("packet.size_word[0]=0x%04xn", packet.size_word[0]);
printf("packet.size_word[1]=0x%04xn", packet.size_word[1]);
Output is
packet.size_word[0]=0x0605
packet.size_word[1]=0x0807
It completely missed 0x03 and 0x04.
When I use the following definition (remove "uint32_t size;"), it works fine.
union packet_t {
uint8_t raw[10];
struct {
union {
uint16_t number;
uint8_t number_byte[2];
};
union {
uint16_t size_word[2];
uint8_t size_byte[4];
};
uint8_t body[4];
};
} packet;
Here is the output:
packet.size_word[0]=0x0403
packet.size_word[1]=0x0605
Does anyone know why this is happening? I thought items in union always occupied same memory location.
Here is the link for the code.
The original Code is here.
--------------------------Update 11/25/2018---------------------------------
So I'm confident now it's the structure padding and it depends on the CPU architecture.
I tested on Arduino with Atmega328p (an 8-bit MCU), it works like a charm. There was no struct padding since the MCU process 1 byte each time.
However, the code is not portable at all as @selbie mentioned, when writing such code, we have to consider CPU architecture and environment. Simplest solution is not using it.
Further reading:
C – Structure Padding
Structure padding and packing
c struct unions packing
c struct unions packing
edited Jan 8 at 16:17
hat
527519
527519
asked Nov 25 '18 at 5:32
xkimixkimi
142
142
4
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
6
2 bytes of padding precede the second union to alignuint32_t sizeto a 4-byte boundary. You can see this with:printf("%zun", offsetof(union packet_t, size));
– Brett Hale
Nov 25 '18 at 5:47
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition ofunion packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.
– eapetcho
Nov 25 '18 at 5:49
1
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39
|
show 2 more comments
4
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
6
2 bytes of padding precede the second union to alignuint32_t sizeto a 4-byte boundary. You can see this with:printf("%zun", offsetof(union packet_t, size));
– Brett Hale
Nov 25 '18 at 5:47
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition ofunion packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.
– eapetcho
Nov 25 '18 at 5:49
1
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39
4
4
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
6
6
2 bytes of padding precede the second union to align
uint32_t size to a 4-byte boundary. You can see this with: printf("%zun", offsetof(union packet_t, size));– Brett Hale
Nov 25 '18 at 5:47
2 bytes of padding precede the second union to align
uint32_t size to a 4-byte boundary. You can see this with: printf("%zun", offsetof(union packet_t, size));– Brett Hale
Nov 25 '18 at 5:47
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition of
union packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.– eapetcho
Nov 25 '18 at 5:49
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition of
union packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.– eapetcho
Nov 25 '18 at 5:49
1
1
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39
|
show 2 more comments
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464932%2fstruct-inside-a-union%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464932%2fstruct-inside-a-union%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
Short answer is padding. Long answer is you should never try serialize or parse network data (or any binary blob) format this way. At least if you want your code to be portable.
– selbie
Nov 25 '18 at 5:46
6
2 bytes of padding precede the second union to align
uint32_t sizeto a 4-byte boundary. You can see this with:printf("%zun", offsetof(union packet_t, size));– Brett Hale
Nov 25 '18 at 5:47
@xkimi. a union is a type that store different data type at the same memory location but not at the same time. Hence, given the definition of
union packet_t, the declaration of packet and the assignment made through the for loop indicates that only packet.raw is set. Therefore, accessing any other data in the union packate_t packet will yield a weird result.– eapetcho
Nov 25 '18 at 5:49
1
I don't know why you are saying "it missed 0x03, 0x04. 0x01 - 0x04 are all contained within packet::size. If you add the statement printf("packet.size=0x%04xn", packet.size); into your main() you will see them there.
– natersoz
Nov 25 '18 at 6:17
@selbie the code is actually intended to run in atmega328p, an 8-bit MCU, it may work in that environment? A really good lesson to learn about structure padding in different archs. Thanks for pointing out. I will try to avoid this in my implementation since it's so architecture dependant.
– xkimi
Nov 25 '18 at 6:39