(轉)程序是怎麼在內存中存儲的

一個程序佔有的內存分爲5類:

1. 全局/靜態數據區---->對應  .data數據段

2.常量數據區--> .rdata只讀數據段

3.代碼區--->  .text代碼段 (存儲代碼)

4.棧

5.堆

 

 

內存存儲情況:

1. 全局/靜態數據區---> 全局/靜態數據

2.常量數據區(.rdata)-->常量字符串

3.棧---->自動變量或者局部變量,以及傳遞的函數參數

4.堆--->用戶控制  new/malloc出來的內存,注意內存泄露問題

 

 

  下面通過具體代碼查看數據的存儲問題:


        

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. int nGlobal = 200;  
  4. int main()  
  5. {  
  6.     char *pLocalString1 = "LocalString1";  
  7.     const char *pLocalString2 = "LocalString2";  
  8.     static int nLocalStatic = 100;  
  9.     int nLocal = 1;  
  10.     const int nLocalConst = 20;  
  11.     int * pNew = (int *)malloc(sizeof(int)*5);;  
  12.     char *pMalloc = (char *)malloc(1);  
  13.     //全局/靜態數據區  
  14.     printf("全局/靜態數據區:/n");  
  15.     printf("global variable:            0x%x/n", &nGlobal);  
  16.     printf("static variable:            0x%x/n/n", &nLocalStatic);  
  17.     //常量區  
  18.     printf("常量區:/n");  
  19.     printf("pLocalString1 variable:     0x%x/n", pLocalString1);  
  20.     printf("pLocalString2 variable:     0x%x/n", pLocalString2);  
  21.     printf("nLocalConst variable:       0x%x/n/n", nLocalConst);  
  22.     //堆  
  23.     printf("堆:/n");  
  24.     printf("new  variable:              0x%x/n", pNew);  
  25.     printf("malloc variable:            0x%x/n/n", pMalloc);  
  26.     //棧  
  27.     printf("棧:/n");  
  28.     printf("pointer pnew variable:      0x%x/n", &pNew);  
  29.     printf("pointer malloc variable:    0x%x/n", &pMalloc);  
  30.     printf("nLocal variable:            0x%x/n", &nLocal);  
  31.     printf("pointer pLocalString1 variable: 0x%x/n", &pLocalString1);  
  32.     printf("pointer pLocalString2 variable: 0x%x/n", &pLocalString2);  
  33.     printf("nLocalConst variable:           0x%x/n/n", &nLocalConst);  
  34.     return 0;  
  35. }  

 

下面是運行結果:

 

我們可以看到棧和堆的內存都存在內存對齊的。 堆的內存是按照34個字節對齊(我的機器是這樣的)的。

下面是各個數據所在區間的對應關係:

轉自:http://blog.csdn.net/icekingson/article/details/6461629

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章