带着问题上路
问题:
(1 为什么栈上分配内存,分配的空间越大,初始化后编译出的文件越大?
(2)为什么初始化字符串编译出的可执行文件会变大?
#include <stdio.h>
#define FIVE 5
#define BUFF_SIZE 65535
//#define BUFF_SIZE 2
int
main()
{
char buff[BUFF_SIZE];
char buff2[BUFF_SIZE];
//memset(buff, 0x0, sizeof(buff));
//memset(buff2, 0x0, sizeof(buff2));
printf("hello word %d %s\n", FIVE, buff);
return 0;
}
/*
编译: gcc -o hello_word_buff hello_word_buff.c
结果如下:
case 1:如果有初始化,即不需要memset,(因为大字节初始化为0编译时时会默认用memset初始化,此时再次调用们set会导致编译的文件增大)一般情况静态分配大于1页时就会自动调用memset(编译出的可执行文件也会变大)
char buff[BUFF_SIZE] = {0};
char buff2[BUFF_SIZE] = {0};
当BUFF_SIZE 为65535时
linux-6ir7:/home/admin/work/test/process/hello # size hello_word_buff
text data bss dec hex filename
1272 268 8 1548 60c hello_word_buff
当BUFF_SIZE 为2时
linux-6ir7:/home/admin/work/test/process/hello # size hello_word_buff
text data bss dec hex filename
1155 264 8 1427 593 hello_word_buff
命令:readelf -s hello_word_buff
66: 08048578 4 OBJECT GLOBAL DEFAULT 17 _fp_hw
67: 0804855c 0 FUNC GLOBAL DEFAULT 16 _fini
68: 00000000 0 FUNC GLOBAL DEFAULT UND memset@@GLIBC_2.0
69: 00000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@@GLIBC_
70: 0804857c 4 OBJECT GLOBAL DEFAULT 17 _IO_stdin_used
71: 0804a010 0 NOTYPE GLOBAL DEFAULT 26 __data_start
72: 0804a014 0 OBJECT GLOBAL HIDDEN 26 __dso_handle
73: 08049f18 0 OBJECT GLOBAL HIDDEN 21 __DTOR_END__
74: 080484b0 97 FUNC GLOBAL DEFAULT 15 __libc_csu_init
75: 00000000 0 FUNC GLOBAL DEFAULT UND printf@@GLIBC_2.0
可以发现多了一部分(相比较case 4, 或者BUFF_SIZE为2时)
68: 00000000 0 FUNC GLOBAL DEFAULT UND memset@@GLIBC_2.0
命令:readelf -S hello_word_buff (BUFF_SIZE=65535和BUFF_SIZE=2)
[15] .text PROGBITS 080483a0 0003a0 0001dc 00 AX 0 0 16 (BUFF_SIZE=65535)
[15] .text PROGBITS 08048370 000370 00019c 00 AX 0 0 16 (BUFF_SIZE=2)
明显BUFF_SIZE越大.test段的大小就越大,编译出的可执行文件就越大
case 2: 相当引用多次memset
char buff[BUFF_SIZE] = {0};
char buff2[BUFF_SIZE] = {0};
memset(buff, 0x0, sizeof(buff));
memset(buff2, 0x0, sizeof(buff2));
linux-6ir7:/home/admin/work/test/process/hello # size hello_word_buff
text data bss dec hex filename
1320 268 8 1596 63c hello_word_buff
case 3:
char buff[BUFF_SIZE];
char buff2[BUFF_SIZE];
memset(buff, 0x0, sizeof(buff));
memset(buff2, 0x0, sizeof(buff2));
linux-6ir7:/home/admin/work/test/process/hello # size hello_word_buff
text data bss dec hex filename
1272 268 8 1548 60c hello_word_buff
linux-6ir7:/home/admin/work/test/process/hello #
case 4: 不加初始化,buff和buff2 没有真正分配内存
char buff[BUFF_SIZE];
char buff2[BUFF_SIZE];
linux-6ir7:/home/admin/work/test/process/hello # size hello_word_buff
text data bss dec hex filename
1155 264 8 1427 593 hello_word_buff
*/