Tencent background Server Development One problem is to calculate the size of a struct's sizeof:
struct STRDATA
{
int m_int;
Char M_char;
Short M_short;
Char M_flag;
}
The system is a 32-bit UNIX machine, what is the value of sizeof (strdata)?
In a 32-bit system, the int type is 4 bytes, the char type is 1 bytes, and short is 2 bytes, so the total space occupied by the above structure is 8 bytes;
However, when the memory storage data when the various types of reasonable alignment, the CPU access to data efficiency is relatively high; for example, on some platforms each read data is from the even address, if the data byte alignment, you may need only one CPU cycle to obtain data.
So, assuming the storage address starts from 0x0000, then the above struct, M_int is 0-3,m_char is 4,m_short is 6-7,m_flag is 8, a total of 9 bytes, in view of 4 byte alignment, so additional 3 bytes are required, So sizeof this struct has a size of 12 bytes.
If you change into
struct STRDATA
{
Short M_short;
Char M_char;
Char M_flag;
int m_int;
}
That would be 8 bytes.
Note that it must be an even address alignment, and the size of the entire struct should also be an integer multiple of the maximum alignment value of the struct body.
Of course, if the single-byte alignment is the ideal memory footprint.
This is the most basic problem, if the answer is wrong, it should be despised.
I hope I can shame and then brave.
Reference Links:
Why do I need byte alignment?
http://blog.csdn.net/zkf11387/article/details/7662450
Explain the structure, class and other memory byte alignment
http://zhangyu.blog.51cto.com/197148/673792/
32-bit vs. 64-bit length comparison
http://blog.csdn.net/sky_qing/article/details/11650497/
"2017-07-01" Linux application Development Engineer interview question record two: about the size of the structure and the memory alignment problem