C语言结构体及其内存布局

时间:2023-03-08 17:46:20

code[class*="language-"], pre[class*="language-"] { color: rgba(51, 51, 51, 1); font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.4; -moz-tab-size: 8; -o-tab-size: 8; tab-size: 8; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none }
pre[class*="language-"] { padding: 0.8em; overflow: auto; border-radius: 3px; background: rgba(245, 245, 245, 1) }
:not(pre)>code[class*="language-"] { padding: 0.1em; border-radius: 0.3em; white-space: normal; background: rgba(245, 245, 245, 1) }
.token.comment, .token.blockquote { color: rgba(150, 152, 150, 1) }
.token.cdata { color: rgba(24, 54, 145, 1) }
.token.doctype, .token.punctuation, .token.variable, .token.macro.property { color: rgba(51, 51, 51, 1) }
.token.operator, .token.important, .token.keyword, .token.rule, .token.builtin { color: rgba(167, 29, 93, 1) }
.token.string, .token.url, .token.regex, .token.attr-value { color: rgba(24, 54, 145, 1) }
.token.property, .token.number, .token.boolean, .token.entity, .token.atrule, .token.constant, .token.symbol, .token.command, .token.code { color: rgba(0, 134, 179, 1) }
.token.tag, .token.selector, .token.prolog { color: rgba(99, 163, 92, 1) }
.token.function, .token.namespace, .token.pseudo-element, .token.class, .token.class-name, .token.pseudo-class, .token.id, .token.url-reference .token.variable, .token.attr-name { color: rgba(121, 93, 163, 1) }
.token.entity { cursor: help }
.token.title, .token.title .token.punctuation { font-weight: bold; color: rgba(29, 62, 129, 1) }
.token.list { color: rgba(237, 106, 67, 1) }
.token.inserted { background-color: rgba(234, 255, 234, 1); color: rgba(85, 165, 50, 1) }
.token.deleted { background-color: rgba(255, 236, 236, 1); color: rgba(189, 44, 0, 1) }
.token.bold { font-weight: bold }
.token.italic { font-style: italic }
.language-json .token.property { color: rgba(24, 54, 145, 1) }
.language-markup .token.tag .token.punctuation { color: rgba(51, 51, 51, 1) }
code.language-css, .language-css .token.function { color: rgba(0, 134, 179, 1) }
.language-yaml .token.atrule { color: rgba(99, 163, 92, 1) }
code.language-yaml { color: rgba(24, 54, 145, 1) }
.language-ruby .token.function { color: rgba(51, 51, 51, 1) }
.language-markdown .token.url { color: rgba(121, 93, 163, 1) }
.language-makefile .token.symbol { color: rgba(121, 93, 163, 1) }
.language-makefile .token.variable { color: rgba(24, 54, 145, 1) }
.language-makefile .token.builtin { color: rgba(0, 134, 179, 1) }
.language-bash .token.keyword { color: rgba(0, 134, 179, 1) }
pre[data-line] { position: relative; padding: 1em 0 1em 3em }
pre[data-line] .line-highlight-wrapper { position: absolute; top: 0; left: 0; background-color: rgba(0, 0, 0, 0); display: block; width: 100% }
pre[data-line] .line-highlight { position: absolute; left: 0; right: 0; margin-top: 1em; background: linear-gradient(90deg, rgba(153, 122, 102, 0.1) 70%, rgba(153, 122, 102, 0)); pointer-events: none; line-height: inherit; white-space: pre }
pre[data-line] .line-highlight:before, pre[data-line] .line-highlight[data-end]:after { content: attr(data-start); position: absolute; top: 0.4em; left: 0.6em; min-width: 1em; padding: 0 0.5em; background-color: rgba(153, 122, 102, 0.4); color: rgba(245, 242, 240, 1); font: bold 65% / 1.5 sans-serif; text-align: center; vertical-align: 0.3em; border-radius: 999px; text-shadow: none; box-shadow: 0 1px rgba(255, 255, 255, 1) }
pre[data-line] .line-highlight[data-end]:after { content: attr(data-end); top: auto; bottom: 0.4em }
html body { font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif; font-size: 16px; line-height: 1.6; color: rgba(51, 51, 51, 1); background-color: rgba(255, 255, 255, 1); overflow: initial; box-sizing: border-box; word-wrap: break-word }
html body>:first-child { margin-top: 0 }
html body h1, html body h2, html body h3, html body h4, html body h5, html body h6 { line-height: 1.2; margin-top: 1em; margin-bottom: 16px; color: rgba(0, 0, 0, 1) }
html body h1 { font-size: 2.25em; font-weight: 300; padding-bottom: 0.3em }
html body h2 { font-size: 1.75em; font-weight: 400; padding-bottom: 0.3em }
html body h3 { font-size: 1.5em; font-weight: 500 }
html body h4 { font-size: 1.25em; font-weight: 600 }
html body h5 { font-size: 1.1em; font-weight: 600 }
html body h6 { font-size: 1em; font-weight: 600 }
html body h1, html body h2, html body h3, html body h4, html body h5 { font-weight: 600 }
html body h5 { font-size: 1em }
html body h6 { color: rgba(92, 92, 92, 1) }
html body strong { color: rgba(0, 0, 0, 1) }
html body del { color: rgba(92, 92, 92, 1) }
html body a:not([href]) { color: inherit; text-decoration: none }
html body a { color: rgba(0, 136, 204, 1); text-decoration: none }
html body a:hover { color: rgba(0, 163, 245, 1); text-decoration: none }
html body img { max-width: 100% }
html body>p { margin-top: 0; margin-bottom: 16px; word-wrap: break-word }
html body>ul, html body>ol { margin-bottom: 16px }
html body ul, html body ol { padding-left: 2em }
html body ul.no-list, html body ol.no-list { padding: 0; list-style-type: none }
html body ul ul, html body ul ol, html body ol ol, html body ol ul { margin-top: 0; margin-bottom: 0 }
html body li { margin-bottom: 0 }
html body li.task-list-item { list-style: none }
html body li>p { margin-top: 0; margin-bottom: 0 }
html body .task-list-item-checkbox { margin: 0 0.2em 0.25em -1.8em; vertical-align: middle }
html body .task-list-item-checkbox:hover { cursor: pointer }
html body blockquote { margin: 16px 0; font-size: inherit; padding: 0 15px; color: rgba(92, 92, 92, 1); border-left: 4px solid rgba(214, 214, 214, 1) }
html body blockquote>:first-child { margin-top: 0 }
html body blockquote>:last-child { margin-bottom: 0 }
html body hr { height: 4px; margin: 32px 0; background-color: rgba(214, 214, 214, 1); border: 0 none }
html body table { margin: 10px 0 15px; border-collapse: collapse; border-spacing: 0; display: block; width: 100%; overflow: auto; word-break: keep-all }
html body table th { font-weight: bold; color: rgba(0, 0, 0, 1) }
html body table td, html body table th { border: 1px solid rgba(214, 214, 214, 1); padding: 6px 13px }
html body dl { padding: 0 }
html body dl dt { padding: 0; margin-top: 16px; font-size: 1em; font-style: italic; font-weight: bold }
html body dl dd { padding: 0 16px; margin-bottom: 16px }
html body code { font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 0.85em !important; color: rgba(0, 0, 0, 1); background-color: rgba(240, 240, 240, 1); border-radius: 3px; padding: 0.2em 0 }
html body code::before, html body code::after { letter-spacing: -0.2em; content: " " }
html body pre>code { padding: 0; margin: 0; font-size: 0.85em !important; word-break: normal; white-space: pre; background: rgba(0, 0, 0, 0); border: 0 }
html body .highlight { margin-bottom: 16px }
html body .highlight pre, html body pre { padding: 1em; overflow: auto; font-size: 0.85em !important; line-height: 1.45; border: rgba(214, 214, 214, 1); border-radius: 3px }
html body .highlight pre { margin-bottom: 0; word-break: normal }
html body pre code, html body pre tt { display: inline; max-width: initial; padding: 0; margin: 0; overflow: initial; line-height: inherit; word-wrap: normal; background-color: rgba(0, 0, 0, 0); border: 0 }
html body pre code:before, html body pre tt:before, html body pre code:after, html body pre tt:after { content: normal }
html body p, html body blockquote, html body ul, html body ol, html body dl, html body pre { margin-top: 0; margin-bottom: 16px }
html body kbd { color: rgba(0, 0, 0, 1); border-top: 1px solid rgba(214, 214, 214, 1); border-right: 1px solid rgba(214, 214, 214, 1); border-bottom: 2px solid rgba(199, 199, 199, 1); border-left: 1px solid rgba(214, 214, 214, 1); padding: 2px 4px; background-color: rgba(240, 240, 240, 1); border-radius: 3px }
@media print { html body { background-color: rgba(255, 255, 255, 1) } html body h1, html body h2, html body h3, html body h4, html body h5, html body h6 { color: rgba(0, 0, 0, 1); page-break-after: avoid } html body blockquote { color: rgba(92, 92, 92, 1) } html body pre { page-break-inside: avoid } html body table { display: table } html body img { display: block; max-width: 100%; max-height: 100% } html body pre, html body code { word-wrap: break-word; white-space: pre } }
.markdown-preview { width: 100%; height: 100%; box-sizing: border-box }
.markdown-preview .pagebreak, .markdown-preview .newpage { page-break-before: always }
.markdown-preview pre.line-numbers { position: relative; padding-left: 3.8em; counter-reset: linenumber 0 }
.markdown-preview pre.line-numbers>code { position: relative }
.markdown-preview pre.line-numbers .line-numbers-rows { position: absolute; pointer-events: none; top: 1em; font-size: 100%; left: 0; width: 3em; letter-spacing: -1px; border-right: 1px solid rgba(153, 153, 153, 1); -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none }
.markdown-preview pre.line-numbers .line-numbers-rows>span { pointer-events: none; display: block; counter-increment: linenumber 1 }
.markdown-preview pre.line-numbers .line-numbers-rows>span:before { content: counter(linenumber); color: rgba(153, 153, 153, 1); display: block; padding-right: 0.8em; text-align: right }
.markdown-preview .mathjax-exps .MathJax_Display { text-align: center !important }
.markdown-preview:not([for="preview"]) .code-chunk .btn-group { display: none }
.markdown-preview:not([for="preview"]) .code-chunk .status { display: none }
.markdown-preview:not([for="preview"]) .code-chunk .output-div { margin-bottom: 16px }
{ width: 8px }
{ border-radius: 10px; background-color: rgba(0, 0, 0, 0) }
{ border-radius: 5px; background-color: rgba(150, 150, 150, 0.66); border: 4px solid rgba(150, 150, 150, 0.66); background-clip: content-box }
html body[for="html-export"]:not([data-presentation-mode]) { position: relative; width: 100%; height: 100%; top: 0; left: 0; margin: 0; padding: 0; overflow: auto }
html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview { position: relative; top: 0 }
@media screen and (min-width: 914px) { html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview { padding: 2em calc(50% - 457px + 2em) } }
@media screen and (max-width: 914px) { html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview { padding: 2em } }
@media screen and (max-width: 450px) { html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview { font-size: 14px !important; padding: 1em } }
@media print { html body[for="html-export"]:not([data-presentation-mode]) #sidebar-toc-btn { display: none } }
html body[for="html-export"]:not([data-presentation-mode]) #sidebar-toc-btn { position: fixed; bottom: 8px; left: 8px; font-size: 28px; cursor: pointer; color: inherit; z-index: 99; width: 32px; text-align: center; opacity: 0.4 }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] #sidebar-toc-btn { opacity: 1 }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc { position: fixed; top: 0; left: 0; width: 300px; height: 100%; padding: 32px 0 48px; font-size: 14px; box-shadow: 0 0 4px rgba(150, 150, 150, 0.33); box-sizing: border-box; overflow: auto; background-color: inherit }
{ width: 8px }
{ border-radius: 10px; background-color: rgba(0, 0, 0, 0) }
{ border-radius: 5px; background-color: rgba(150, 150, 150, 0.66); border: 4px solid rgba(150, 150, 150, 0.66); background-clip: content-box }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc a { text-decoration: none }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc ul { padding: 0 1.6em; margin-top: 0.8em }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc li { margin-bottom: 0.8em }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc ul { list-style-type: none }
html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview { left: 300px; width: calc(100% - 300px); padding: 2em calc(50% - 457px - 150px); margin: 0; box-sizing: border-box }
@media screen and (max-width: 1274px) { html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview { padding: 2em } }
@media screen and (max-width: 450px) { html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview { width: 100% } }
html body[for="html-export"]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .markdown-preview { left: 50%; transform: translateX(-50%) }
html body[for="html-export"]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .md-sidebar-toc { display: none }

C语言结构体

  1. 结构体的定义

    结构体的定义要使用struct关键字,并以";"结尾。

    下面找个微软定义的结构体:

    typedef struct _FILETIME {
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
    } FILETIME, *PFILETIME, *LPFILETIME;

    可以看出在定义结构体时使用了typedef,为_FILETIME起了一个别名,并定义了指向改结构

    的指针PFILETIME。

  2. 结构体变量的初始化与赋值操作

    • 使用初始化列表进行初始化

      例如:
        FILETIME ft = { 88,99 };
      

      还可以使用memset进行清零初始化:

      FILETIME ft
      memset(&ft,0,sizeof(ft));
    • 结构体变量赋值

      C++11标准之前只能在结构体变量初始化的时候可以使用列表进行初始化,

      现在支持C++11标准的编译器可以在任意场合使用列表进行赋值,编译时不会报错.

      例:

      C语言结构体及其内存布局

      C++11标准还可以直接在定义结构体时为每个成员指定初值,例:

      C语言结构体及其内存布局

      但是最后还是不要使用新标准这两个特性,因为在不支持C++11标准的编译器上会报错,
  3. 一个空结构体的大小

    一个空结构体的大小为1字节,而不是零字节

    例:

    C语言结构体及其内存布局

  4. 计算结构体大小

    • 结构体成员对齐值
    typedef struct tagTest
    {
    char m_chTest;
    int m_nTest;
    }TEST;

    上面这个结构体的大小是多少呢?如果你不知道内存对齐,那么很可能认为认为其大小为5字节,

    但其实这个结构体的真实大小可能为5字节,也有可能为6字节,也有可能是8字节.

    结构体的大小与结构体的成员对齐值有关,设置不同的成员对齐值,将使得同一个结构体有不同大小,

    可以在VS的项目->属性->C/C++->代码生成,设置所有的结构体成员对齐值:

    C语言结构体及其内存布局

    VC++编译器共支持1,2,4,8,16这五个对齐值,默认对齐值为8.如果结构体成员对齐值是1,那么表示结构体

    成员不对齐,在这种情况下上面例子中的TEST的大小为5.

    还可以使用/Zp命令来这设置结构体成员对齐值:

    C语言结构体及其内存布局

    但是对齐值必须是1,2,4,8,16,如果指定为其他值编译器编译时会给出警告,并自行选择合理的编译对齐值:

    C语言结构体及其内存布局

    上面这两种设置成员对齐值的方法是设置所有结构体的成员对齐值,但是有时我只想设置单个结构体的成员对齐值,

    那么可以使用编译预处理指令#pragma pack来设置,例如:

      #pragma pack(push,1)
    typedef struct tagTest
    {
    char m_chTest;
    int m_nTest;
    }TEST; #pragma pack(pop)

    #pragma pack(push,1)中的push表示保存当前的结构体成员对齐值,然后将结构体成员对齐值设置1,

    #pragma pack(pop)表示恢复结构体成员对齐值为上次保存的结构体对齐值,那么加载这两条编译预

    处理命令间定义的结构体的成员对齐值全部为1

  • 结构体大小计算

    (1)设结构体成员对齐值为ZP

    (2)设结构体当前数据成员对齐值zp=min(当前数据成员类型大小,ZP)

    (3)设结构体自身对齐值stAlign=min(max(数据成员1类型大小,.....数据成员n类型大小),ZP)

    (4)设置结构体某成员距离结构体首地址的偏移为offset

    (5)每个成员的位置偏移(也就是offset)要对zp取余,如果余数不为0,则要调整位置偏移,

    在大于当前偏移值中找一个最小的位置偏移,使之能够对zp取余且余数为0,最后结构体

    的总大小要对stAlign取余,如果余数不为0,采用相同的方法调整结构体大小

    注意:如果结构体中有成员为数组,例如:

         struct tagTest
    {
    char m_ch;
    int m_nAry[10];
    };
        那么m_nAry的数据类型大小为4字节,而不是40字节
    
        如果结构体A中有另一个结构体B作为作为结构体A的数据成员,例如:
    
         #pragma pack(push,8)
    struct B
    {
    char m_ch;
    int m_nAry[10];
    }; struct A
    {
    B m_b;
    char m_ch;
    int m_nAry[10];
    };
    #pragma pack(pop)
        那么在结构体A中m_b的对齐值为为结构体B的自身对齐值,也就是4,在计算结构体A
    的自身对齐值时,并不是将sizeof(m_b)参与计算,而是取结构体B中宽度最大的基本
    数据类型所占字节参与计算,例如结构体B中宽度最大的基本数据类型为int,也就是
    4字节,所以结构体A的自身对齐值为min(max(4,1,4),8)=4

    例1:

       #pragma pack(push,8)
    typedef struct tagTestA
    {
    char m_chTest;
    int m_nTest;
    float m_fTest;
    char m_chAry[13];
    };
    #pragma pack(pop)
    • 结构体成员对齐值为ZP=8,结构体自身对齐值stAlign为:

      min(max(sizeof(char),sizeof(int),sizeof(int),sizeof(float),sizeof(char)),ZP)=4

    • m_chTest的对齐值zp=min(sizeof(char),ZP)=1,m_chTest为结构体第一个成员,所以其相对结

      构体首地址偏移量offset=0,offset对zp取余结果为0,所以无需调整,则下一个成员m_nTest相对

      于结构体首地址的偏移为offset+sizeof(m_chTest)=1

    • m_nTest的对齐值zp=min(sizeof(int),ZP)=4,m_nTest相对首地址的偏移量offset=1,

      offset%zp=1,取余结果不为0,当offset调整为4时,取余结果为0,则下一个成员m_fTest相对于

      结构体首地址的偏移为offset+sizeof(m_nTest)=8

    • m_fTest的对齐值zp=min(sizeof(float),ZP)=4,m_nTest相对首地址的偏移量offset=8,

      offset%zp=0,取余结果为0,无需调整,则下一个成员m_chAry相对于结构体首地址的偏移为

      offset+sizeof(m_fTest)=12

    • m_chAry的对齐值zp=min(sizeof(char),ZP)=1,m_chAry相对首地址的偏移量offset=12,

      offset%zp=0,无需调整,至此结构体tagTestA最后一个成员的偏移计算完毕,结构体大小为

      offset+sizeof(m_chAry)=25, 25%stAlign != 0,所以结构体总大小需要调整,那么大于25且能

      够对4取余为0的最小值为28,所以结构体大小为28,那么下面来验证下计算结果:

      C语言结构体及其内存布局

    测试代码中计算结构体偏移使用了宏函数offsetof,其定义在stddef.h中:

    #if defined(_MSC_VER) && !defined(_CRT_USE_BUILTIN_OFFSETOF)
    #ifdef __cplusplus
    #define offsetof(s,m) ((size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
    #else
    #define offsetof(s,m) ((size_t)&(((s*)0)->m))
    #endif
    #else
    #define offsetof(s,m) __builtin_offsetof(s,m)
    #endif

    ((size_t)&(((s*)0)->m)):(s*)0先是将0地址强行解释为s类型的指针,然后(s*)0)->m引用结构体的

    成员m,&(((s*)0)->m))取得成员m的内存地址,因为该指针指向0地址,所

    以强转后就得到成员m相对于结构体首地址的偏移,虽然是指向0地址的指针

    但是并未使用该指针对结构体成员进行赋值和取值操作,所以不会引发崩溃。

例2:

  #pragma pack(push,8)
typedef struct tagTestA
{
char m_chTest;
int m_nTest;
float m_fTest;
char m_chAry[13];
};
#pragma pack(pop) #pragma pack(push,4)
struct tagTestB
{
double m_dbTest1;
char m_chTest2;
tagTestA m_stA;
char m_ch[7];
};
#pragma pack(pop)

结构体tagTestB的计算有点复杂,首先它的结构体成员对齐值设置为4,其次,它的一个数据成员为结构体tagTestA类型,下面开始计算:

  • 根据例1中的计算结构体tagTestA的自身对齐值为4,tagTestA的的大小为28;

    tagTestB的成员对齐值ZP=4

    tagTestB的自身对齐值stAlign=min(max(sizeof(double),sizeof(char),4,sizeof(char)),ZP)=4

  • m_dbTest1为结构体第一个成员,距离结构体的首地址偏移offset=0,m_dbTest1的自身对齐值

    zp=min(sizeof(double),ZP)=4,offset%zp=0,所以无需调整offset,那么下一个成员m_chTest2

    相对于结构体首地址的偏移为offset+sizeof(double)=8

  • 根据上一步,m_chTest2距离结构体首地址的偏移offset=8,m_chTest2的自身对齐值

    zp=min(sizeof(char),ZP)=1,offset%zp=0,所以offset无需调整,则下一个数据成员m_stA

    距离结构体首地址的偏移为offset+sizeof(char)=9

  • 根据上一步,m_stA距离结构体首地址的偏移offset=9,m_stA的自身对齐值zp=min(4,ZP)=4,

    offset%zp!=0,offset需要调整,将offset调整为12时满足offset%zp=0,则下一个成员m_ch

    距离结构体首地址的偏移为offset+sizeof(m_ch)=40

  • 根据上一步,m_ch距离结构体首地址的偏移offset=40,m_ch的自身对齐值为zp=min(sizeof(char),ZP)=1,

    offset%zp=0,所以offset无需调整,则结构体tagTestB的大小为offset+sizeof(m_ch)=47,

    且47%stAlign!=0,所以结构体大小需要调整,当结构体大小为48时,满足要求

    通过以上计算可以得出m_dbTest1的偏移为0,m_chTest2的偏移为8,m_stA的偏移为12,m_ch的偏移为40,

    结构体总大小为48,下面在VS中验证结果:

    C语言结构体及其内存布局

注意事项:

  • 以上是VC++编译器根据不同结构体成员对齐值实现内存布局的解析,其他编译器的实现可能有所不同

  • 当结构体成员对齐值为1时,表示结构体成员不进行内存对齐,各个成员紧紧相邻,不会有填充字节,

    那么此时结构体大小为sizeof(member1)+..........sizeof(membern)

相关文章