本文介绍了为什么需要存在.bss段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所知道的是,全局和静态变量保存在。数据段和未初始化的数据都在的.bss 段。我不明白的是,为什么我们未初始化变量专用段?如果一个未初始化的变量在运行时赋值,不变量仍然存在于的.bss 段只?

在下面的程序中, A 。数据段和 B 的.bss 段;那是对的吗?请纠正我,如果我的理解是错误的。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释一个[10] = {1,2,3,4,5,6,7,8,9};
INT B〔20〕; / *未初始化,所以在.bss段和20 *的sizeof(int)的不占空间* /诠释的main()
{
   ;
}

此外,考虑下面的程序,

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
INT变种[10]; / *未初始化所以在.bss段* /
诠释的main()
{
   VAR [0] = 20 / * **初始化,在这种变种会是什么?** * /
}


解决方案

究其原因是为了减少程序大小。试想一下,你的C程序的嵌入式系统,其中code和所有的常量都保存在真正的ROM(闪存)上运行。在这种系统中,初始的复制下来必须执行将所有静态存储持续时间的对象,之前的主()被调用。它通常会是这样的伪:

 为(i = 0; I< all_explicitly_initialized_objects;我++)
{
  。数据[I] = init_value [I]
}memset的(.bss段,
       0,
       all_implicitly_initialized_objects);

其中的.data和.bss被存储在RAM中,但init_value存储在ROM中。如果它一直一个段,则该光盘必须与大量的零来填充,显著增加ROM的大小

基于RAM的可执行文件同样的工作,但他们当然没有真正的ROM。

另外,memset的很可能一些非常有效的联汇编,这意味着该启动拷贝下来可以执行得更快。

What I know is that global and static variables are stored in the .data segment, and uninitialized data are in the .bss segment. What I don't understand is why do we have dedicated segment for uninitialized variables? If an uninitialised variable has a value assigned at run time, does the variable exist still in the .bss segment only?

In the following program, a is in the .data segment, and b is in the .bss segment; is that correct? Kindly correct me if my understanding is wrong.

#include <stdio.h>
#include <stdlib.h>

int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
int b[20]; /* Uninitialized, so in the .bss and will not occupy space for 20 * sizeof (int) */

int main ()
{
   ;
}

Also, consider following program,

#include <stdio.h>
#include <stdlib.h>
int var[10];  /* Uninitialized so in .bss */
int main ()
{
   var[0] = 20  /* **Initialized, where this 'var' will be ?** */
}
解决方案

The reason is to reduce program size. Imagine that your C program runs on an embedded system, where the code and all constants are saved in true ROM (flash memory). In such systems, an initial "copy-down" must be executed to set all static storage duration objects, before main() is called. It will typically go like this pseudo:

for(i=0; i<all_explicitly_initialized_objects; i++)
{
  .data[i] = init_value[i];
}

memset(.bss,
       0,
       all_implicitly_initialized_objects);

Where .data and .bss are stored in RAM, but init_value is stored in ROM. If it had been one segment, then the ROM had to be filled up with a lot of zeroes, increasing ROM size significantly.

RAM-based executables work similarly, though of course they have no true ROM.

Also, memset is likely some very efficient inline assembler, meaning that the startup copy-down can be executed faster.

这篇关于为什么需要存在.bss段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:08