写了一段代码,验证了一下内存的分布情况:
#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.局部的静态变量虽然存储在全局数据区,但是作用域只能在所在的函数中,对其他函数不可见。