linux C++ 的內存分佈情況

寫了一段代碼,驗證了一下內存的分佈情況:

#include <iostream>
using namespace std;
int k = 300;
static int global_static = 0;
const int i = 100;
#define n 10
const int j = 200;
int fun (int i = 1, int j =2)
{
    const int k = 3;
    static int l =0;
    char *p = new char[n+1];
    int m;
    for(m = 0; m < n ; m ++)
        *(p + m) = 'A'+ m;
    *(p + m) = '\0';
    cout << "Address of parameter variable:"<<endl;
    cout << "&i = " << &i << "\t" << "&j = " << &j <<endl;
    cout << "Address of local variable:" << endl;
    cout << "&k = " << &k << "\t" << "&p = " << &p << "\t" << "&m = "<< &m <<endl;
    cout << "Address of static local variable:" << endl;
    cout << "&l = "<< &l << endl;
    cout << "Address of heap: " << (void *)p << endl;
    cout << "before delete p =" << p << endl;
    delete []p;
    cout << "after delete: "<< (void *)p <<endl;
    cout << "p =" << p << endl;
    return 0;
}


int main()
{
    fun();
    cout << "Address of global variable: " << endl;
    cout << "&i = " << &i << "\t" << "&j = " << &j << "\t" << "&k = " << &k << endl;
    cout << "Address of function: " << endl;
    cout << "&fun = " << &fun << "\t" << "&main =" << &main << endl;
    cout << "&global_static = " << &global_static << endl;
    int block;
    cin >> block;
    return 0;
}

輸出結果

Address of parameter variable:
&i = 0x7fff61c8c7cc     &j = 0x7fff61c8c7c8
Address of local variable:
&k = 0x7fff61c8c7d8     &p = 0x7fff61c8c7d0     &m = 0x7fff61c8c7dc
Address of static local variable:
&l = 0x6022c8
Address of heap: 0x2168010
before delete p =ABCDEFGHIJ
after delete: 0x2168010
p =
Address of global variable: 
&i = 0x400fb4   &j = 0x400fb8   &k = 0x602070
Address of function: 
&fun = 1        &main =1
&global_static = 0x6022c4

=========================分割線===================

先說明幾個概念:

在全局中定義的叫做全局數據類型,在某個函數中定義的叫做局部數據類型。

使用static修飾的叫做靜態變量,使用const修飾的叫做常量

靜態變量是i可以修改的,但是全局只有一個,但是常量是不能修改的。

靜態變量(使用static修飾的,無論局部還是全局),全局變量,全局常量都在全局數據區中。需要注意的是:

1.局部的常量是存在棧中的,改局部常量在它的作用域中是不可修改的,但是當它所在的函數退出之後,該常量也會隨之被析構。所以不能將局部常量的值作爲返回值使用。

2.局部的靜態變量雖然存儲在全局數據區,但是作用域只能在所在的函數中,對其他函數不可見。


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