Reputation: 339
The following code:
#include <stdint.h>
uint8_t byte = 0x12;
uint16_t word = 0x1234;
int main(int argc, char *argv[])
{
return 0;
}
Inspecting the .data
section, it shows that byte
variable 2 bytes, not 1 as uint8_t
promises:
Hex dump of section '.data':
0x00601020 00000000 00000000 00000000 00000000 ................
0x00601030 12003412 ..4.
How can we ensure that byte
is 1 byte, even it makes the memory misaligned? I tried adding #pragam pack(1)
but it's still the same.
Upvotes: 2
Views: 249
Reputation: 21886
byte variable 2 bytes, not 1 as uint8_t promises
Variable is 1 but compiler pads it to 2 bytes. Note that this does not affect total section size (it'll still be aligned to 2 bytes).
How can we ensure that byte is 1 byte, even it makes the memory misaligned?
Why would you want to do that? On many platforms this will cause compiler to generate inefficient code for memory accesses so you'll loose anything you squeeze from variable alignments due to code size increase. If you absolutely must use unaligned globals, mark them with __attribute__((aligned(1)))
.
Upvotes: 1