一個程序佔有的內存分爲5類:
1. 全局/靜態數據區---->對應 .data數據段
2.常量數據區--> .rdata只讀數據段
3.代碼區---> .text代碼段 (存儲代碼)
4.棧
5.堆
內存存儲情況:
1. 全局/靜態數據區---> 全局/靜態數據
2.常量數據區(.rdata)-->常量字符串
3.棧---->自動變量或者局部變量,以及傳遞的函數參數
4.堆--->用戶控制 new/malloc出來的內存,注意內存泄露問題
下面通過具體代碼查看數據的存儲問題:
- #include <stdio.h>
- #include <stdlib.h>
- int nGlobal = 200;
- int main()
- {
- char *pLocalString1 = "LocalString1";
- const char *pLocalString2 = "LocalString2";
- static int nLocalStatic = 100;
- int nLocal = 1;
- const int nLocalConst = 20;
- int * pNew = (int *)malloc(sizeof(int)*5);;
- char *pMalloc = (char *)malloc(1);
- //全局/靜態數據區
- printf("全局/靜態數據區:/n");
- printf("global variable: 0x%x/n", &nGlobal);
- printf("static variable: 0x%x/n/n", &nLocalStatic);
- //常量區
- printf("常量區:/n");
- printf("pLocalString1 variable: 0x%x/n", pLocalString1);
- printf("pLocalString2 variable: 0x%x/n", pLocalString2);
- printf("nLocalConst variable: 0x%x/n/n", nLocalConst);
- //堆
- printf("堆:/n");
- printf("new variable: 0x%x/n", pNew);
- printf("malloc variable: 0x%x/n/n", pMalloc);
- //棧
- printf("棧:/n");
- printf("pointer pnew variable: 0x%x/n", &pNew);
- printf("pointer malloc variable: 0x%x/n", &pMalloc);
- printf("nLocal variable: 0x%x/n", &nLocal);
- printf("pointer pLocalString1 variable: 0x%x/n", &pLocalString1);
- printf("pointer pLocalString2 variable: 0x%x/n", &pLocalString2);
- printf("nLocalConst variable: 0x%x/n/n", &nLocalConst);
- return 0;
- }
下面是運行結果:
我們可以看到棧和堆的內存都存在內存對齊的。 堆的內存是按照34個字節對齊(我的機器是這樣的)的。
下面是各個數據所在區間的對應關係:
轉自:http://blog.csdn.net/icekingson/article/details/6461629