學習結構體之後,就想着來看看棧上多個變量的位址的配置設定情況,是不是也有某種規則一個接一個挨着。不想發現連續的兩個變量的位址并不連續,可以說分得很開,而且從高位址到低位址配置設定。
雖然并不知道系統(還是編譯器? 誰告訴我下)為什麼這麼做,但索性寫了個程式也看看其它區域是怎麼配置設定位址的。
小代碼如下,如果有錯誤,請留言,我會從心底裡感謝你的。
#include <stdio.h>
#include <string.h>
#include <cstdlib>
//列印整形數組
void printfarr(unsigned long *arr, size_t size){
for (size_t i = ; i < size; i++)
{
printf("%x ", arr[i]);
}
printf("\n");
}
//根據傳入的數組arr,比較大小,在out上對應标上其大小的順序值
//總覺得這個算順序的辦法好笨,誰有更好的麻煩貢獻出來
void sx(unsigned long* arr, unsigned long *out, size_t size){
memset(out, -, size*sizeof(unsigned long));
for (size_t i = ; i < size; i++)
{
int min;
for (size_t j = ; j < size; j++)
{
if (out[j]==-)
{
out[j] = i + ;
min = j;
break;
}
}
for (size_t k = min + ; k < size; k++)
{
if((out[k]==-) && (arr[k] < arr[min])){
out[min] = -;
out[k] = i + ;
min = k;
}
}
}
}
//全局區(靜态區)(static)
int static1 = ;
int static2 = ;
int static3 = ;
//文字常量區
const char *str1 = "abc";
const char *str2 = "abc";
const char *str3 = "abcd";
const char *str4 = "abcde";
//程式代碼區
void testadd1(){ int a; }
void testadd2(){ int b; }
void testadd(){
//棧區
int stack1 = ;
int stack2 = ;
int stack3 = ;
//堆區位址
int *heap1 = (int *)malloc(sizeof(int));
int *heap2 = (int *)malloc(sizeof(int));
int *heap3 = (int *)malloc(sizeof(int));
printf("程式代碼區的位址\n");
printf("testadd1=%x\n", testadd1);
printf("testadd2=%x\n", testadd2);
printf("testadd=%x\n", testadd);
printf("文字常量區 常量的位址\n");
printf("str1=%x\n", str1);
printf("str2=%x\n", str2);
printf("str3=%x\n", str3);
printf("str4=%x\n", str4);
printf("全局區(靜态區)(static)變量的位址\n");
printf("&static1=%x\n", &static1);
printf("&static2=%x\n", &static2);
printf("&static3=%x\n", &static3);
printf("棧區 變量的位址\n");
printf("&stack1=%x\n", &stack1);
printf("&stack2=%x\n", &stack2);
printf("&stack3=%x\n", &stack3);
printf("堆區 空間的位址\n");
printf("heap1=%x\n", heap1);
printf("heap2=%x\n", heap2);
printf("heap3=%x\n", heap3);
unsigned long a[] = { (unsigned long)testadd1, (unsigned long)str1, (unsigned long)&static1, (unsigned long)&stack1, (unsigned long)heap1 };
unsigned long a1[];
sx(a, a1, );
printfarr(a, );
printfarr(a1, );
printf("\n");
}
int main()
{
testadd();
//testsx();
return ;
}
多次運作結果

經過多次測試發現:
1,從低到高配置設定位址的有: 程式代碼區、文字常量區、全局靜态區。
2,從高到低配置設定位址的有:棧區
3,堆嗎,找到合适的空間就配置設定,當然無序了。
另外發現:
1,文字常量區總是在程式代碼區之後,而全局靜态區總是在文字常量區之後。
2,棧區、堆區不會出現在第1條這三者的中間。可能在這他們的前面,也可能後面,也可能兩邊。
3,在我的電腦上(intel +win10+vs2013)棧區總是在堆區的前面。但在一個代碼測試工具的網站上卻會出現棧位址在對位址後面的情況。
我電腦上的位址配置設定就是這個意思