C/C++變量在內(nèi)存中的分布
變量在內(nèi)存地址的分布為:堆-棧-代碼區(qū)-全局靜態(tài)-常量數(shù)據(jù)。下面是小編為大家整理的C/C++變量在內(nèi)存中的分布,歡迎參考~
C/C++變量在內(nèi)存中的分布在筆試時經(jīng)常考到,雖然簡單,但也容易忘記,因此在這作個總結(jié),以加深印象。
先寫一個測試程序:
代碼如下:
#include
#include
int g_i = 100;
int g_j = 200;
int g_k, g_h;
int main()
{
const int MAXN = 100;
int *p = (int*)malloc(MAXN * sizeof(int));
static int s_i = 5;
static int s_j = 10;
static int s_k;
static int s_h;
int i = 5;
int j = 10;
int k = 20;
int f, h;
char *pstr1 = "MoreWindows123456789";
char *pstr2 = "MoreWindows123456789";
char *pstr3 = "Hello";
printf("堆中數(shù)據(jù)地址:0x%08x ", p);
put' ');
printf("棧中數(shù)據(jù)地址(有初值):0x%08x = %d ", &i, i);
printf("棧中數(shù)據(jù)地址(有初值):0x%08x = %d ", &j, j);
printf("棧中數(shù)據(jù)地址(有初值):0x%08x = %d ", &k, k);
printf("棧中數(shù)據(jù)地址(無初值):0x%08x = %d ", &f, f);
printf("棧中數(shù)據(jù)地址(無初值):0x%08x = %d ", &h, h);
put' ');
printf("靜態(tài)數(shù)據(jù)地址(有初值):0x%08x = %d ", &s_i, s_i);
printf("靜態(tài)數(shù)據(jù)地址(有初值):0x%08x = %d ", &s_j, s_j);
printf("靜態(tài)數(shù)據(jù)地址(無初值):0x%08x = %d ", &s_k, s_k);
printf("靜態(tài)數(shù)據(jù)地址(無初值):0x%08x = %d ", &s_h, s_h);
put' ');
printf("全局數(shù)據(jù)地址(有初值):0x%08x = %d ", &g_i, g_i);
printf("全局數(shù)據(jù)地址(有初值):0x%08x = %d ", &g_j, g_j);
printf("全局數(shù)據(jù)地址(無初值):0x%08x = %d ", &g_k, g_k);
printf("全局數(shù)據(jù)地址(無初值):0x%08x = %d ", &g_h, g_h);
put' ');
printf("字符串常量數(shù)據(jù)地址:0x%08x 指向 0x%08x 內(nèi)容為-%s ", &pstr1, pstr1, pstr1);
printf("字符串常量數(shù)據(jù)地址:0x%08x 指向 0x%08x 內(nèi)容為-%s ", &pstr2, pstr2, pstr2);
printf("字符串常量數(shù)據(jù)地址:0x%08x 指向 0x%08x 內(nèi)容為-%s ", &pstr3, pstr3, pstr3);
free(p);
return 0;
}
運行結(jié)果(Release版本,XP系統(tǒng))如下:
可以看出:
1. 變量在內(nèi)存地址的分布為:堆-棧-代碼區(qū)-全局靜態(tài)-常量數(shù)據(jù)
2. 同一區(qū)域的各變量按聲明的順序在內(nèi)存的中依次由低到高分配空間(只有未賦值的全局變量是個例外)
3. 全局變量和靜態(tài)變量如果不賦值,默認為0。 棧中的變量如果不賦值,則是一個隨機的數(shù)據(jù)。
4. 編譯器會認為全局變量和靜態(tài)變量是等同的,已初始化的全局變量和靜態(tài)變量分配在一起,未初始化的全局變量和靜態(tài)變量分配在另一起。
上面程序全在一個主函數(shù)中,下面增加函數(shù)調(diào)用,看看函數(shù)的參數(shù)和函數(shù)中變量會分配在什么地方。
程序如下:
代碼如下:
#include
void fun(int i)
{
int j = i;
static int s_i = 100;
static int s_j;
printf("子函數(shù)的參數(shù): 0x%p = %d ", &i, i);
printf("子函數(shù) 棧中數(shù)據(jù)地址: 0x%p = %d ", &j, j);
printf("子函數(shù) 靜態(tài)數(shù)據(jù)地址(有初值): 0x%p = %d ", &s_i, s_i);
printf("子函數(shù) 靜態(tài)數(shù)據(jù)地址(無初值): 0x%p = %d ", &s_j, s_j);
}
int main()
{
int i = 5;
static int s_i = 100;
static int s_j;
printf("主函數(shù) 棧中數(shù)據(jù)地址: 0x%p = %d ", &i, i);
printf("主函數(shù) 靜態(tài)數(shù)據(jù)地址(有初值): 0x%p = %d ", &s_i, s_i);
printf("子函數(shù) 靜態(tài)數(shù)據(jù)地址(無初值): 0x%p = %d ", &s_j, s_j);
put' ');
fun(i);
return 0;
}
運行結(jié)果如下:
可以看出,主函數(shù)中棧的地址都要高于子函數(shù)中參數(shù)及棧地址,證明了棧的伸展方向是由高地址向低地址擴展的。主函數(shù)和子函數(shù)中靜態(tài)數(shù)據(jù)的地址也是相鄰的,說明程序會將已初始化的全局變量和靜態(tài)變量分配在一起,未初始化的全局變量和靜態(tài)變量分配在一起。
【C/C++變量在內(nèi)存中的分布】相關文章:
C/C++內(nèi)存管理05-05
C/C++的浮點數(shù)在內(nèi)存中的存儲方式分析及實例08-13
C++類的成員變量和成員函數(shù)06-01