歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言可執行文件的內存結構

C語言可執行文件的內存結構

日期:2017/3/1 9:41:43   编辑:Linux編程

以前看過C可執行文件的內存結構,但都只是當時很清楚,時候就忘的差不多了,沒有細細去品味,一段時間就忘得差不多了,今天看了一些書籍和博文,決定將C可執行文件的內存結構的內容通過博客記錄下來。

下面是一張C可執行文件的內存結構:

可見進程的邏輯地址空間可分為代碼段,數據段,bss段,以及堆和棧段。這些段存放的數據分別是:

代碼段:存放二進制程序,和常量。

可通過size命令查看可執行文件的各個段的大小:

#include <stdio.h>

int main(int argc,char *argv[])

{

printf("hello world");

}

[root@bogon cstudy]# gcc 8.c

[root@bogon cstudy]# size a.out

text data bss dec hex filename

1157 492 16 1665 681 a.out

#include <stdio.h>

int main(int argc,char *argv[])

{

char *p="aaaa";//常量,應該放在text段

printf("hello world");

}

[root@bogon cstudy]# gcc 8.c

[root@bogon cstudy]# size a.out

text data bss dec hex filename

1162 492 16 1670 686 a.out

可以發現text字段增加了5個字節,aaaa\0正好就是五個字節。

數據段:存放全局的或者靜態的初始化變量

#include <stdio.h>

int main(int argc,char *argv[])

{

printf("hello world");

}

[root@bogon cstudy]# gcc 8.c

[root@bogon cstudy]# size a.out

text data bss dec hex filename

1157 492 16 1665 681 a.out

#include <stdio.h>

int a = 6;

int main(int argc,char *argv[])

{

static int b = 6;

printf("hello world");

}

[root@bogon cstudy]# size a.out

text data bss dec hex filename

1157 500 16 1673 689 a.out

可見data數據段增加了八個字節正好是兩個int型變量。

但是如果變量未初始化,或者變量初始化為0是不放在數據段的,而是放在bss段。

#include <stdio.h>

int a = 0;

int main(int argc,char *argv[])

{

static int b;

printf("hello world");

}

[root@bogon cstudy]# gcc 8.c

[root@bogon cstudy]# size a.out

text data bss dec hex filename

1157 492 24 1673 689 a.out


BSS段:存放未初始化的全局或者靜態變量,或者初始化為0的全局或者靜態變量。


堆段:一般是用戶手動分配的,也就是通過malloc函數來手動分配內存的。

棧段:由編譯器自動分配釋放 ,存放函數的參數值,局部變量的值等

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

將C語言梳理一下,分布在以下10個章節中:

  1. Linux-C成長之路(一):Linux下C編程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成長之路(二):基本數據類型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成長之路(三):基本IO函數操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成長之路(四):運算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成長之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成長之路(六):函數要義 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成長之路(七):數組與指針 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成長之路(八):存儲類,動態內存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成長之路(九):復合數據類型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成長之路(十):其他高級議題

Copyright © Linux教程網 All Rights Reserved