【问题标题】:memory footprint section in cc中的内存占用部分
【发布时间】:2015-06-06 01:57:46
【问题描述】:

当您在 c 中收集内存占用时,您能解释一下这些部分的含义吗? 我可以看到 .text 是源代码,我假设 .const 和 .data 是全局数据和常量(但不太确定),.bss 是什么意思?

| .text    | .const    | .data     | .bss      |

【问题讨论】:

    标签: c memory


    【解决方案1】:

    您可以找到一些答案here。这也涵盖了运行时管理部分 heapstack(这是原始答案)。

    简而言之(扩展):

    • .bss 用于声明 static 并具有全局范围的未初始化变量。这实际上并未存储在文件中,而只是在调用 `main() 之前在运行时保留和清除。
    • .data 包含显式初始化的变量。
    • .const 包含 const 声明的对象。
    • .text 是存储程序代码的地方。注意不是源代码,而是编译后的程序代码!

    在包含调试信息等的普通“ELF”目标文件中还有大量其他部分。

    如需更多信息,请阅读目标文件格式。使用最广泛的一种是ELF

    【讨论】:

      【解决方案2】:

      .bss 是未初始化的static 变量。

      // foo ends up in bss (because it is not explicitly initialised)
      // it's initial value is whatever the default 'zero' value for the type is.
      static int foo;
      // bar ends up in .data
      // (because) it is initialised with the value 42. 
      static int bar = 42;
      // baz ends up in .const
      // (because) it is initialised with a value (22) and the object is const.
      // meaning that the value cannot be allowed to change, meaning the object
      // can be safely mapped to read-only memory pages (if supported).
      static const int baz = 22;
      // code goes in .text:
      int main() { return 0; }
      

      【讨论】:

      • 那么 .const 只是常量而 .data 是全局变量吗?
      • @CBK 添加了带有 cmets 的代码示例来解释它是如何工作的。
      • 不过,它不仅适用于 static 变量。它适用于所有零初始化变量,static 与否。
      • @Dolda2000 不是具有自动存储持续时间的零初始化变量!
      【解决方案3】:

      bss(Block Started by Symbol) 存储零值初始化的静态分配变量(包括globalstatic 变量)。如果静态分配的初始化值不是0,例如:

      int global = 5;
      

      那么global会被分配到data部分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 2012-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多