声明两点:
(1)开发测试环境为VS2010+WindowsXP32位;
(2)内存布局指的是虚拟内存地址,不是物理地址。
1.测试代码
- #include <iostream>
- using namespace std;
- int g_int_a;
- int g_int_b;
- void f_1()
- {
- cout<<"I'm f_1"<<endl;
- }
- void f_2()
- {
- cout<<"I'm f_2"<<endl;
- }
- int main(int argc, char** argv)
- {
- int a;
- int b;
- static int sa;
- static int sb;
- int* h1 = new int;
- int* h2 = new int;
- cout<<"argc的地址是 :"<<std::hex<<std::showbase<<&argc<<endl;
- cout<<"argv的地址是 :"<<std::hex<<std::showbase<<&argv<<endl;
- cout<<"g_int_a的地址是:"<<std::hex<<std::showbase<<&g_int_a<<endl;
- cout<<"g_int_b的地址是:"<<std::hex<<std::showbase<<&g_int_b<<endl;
- cout<<"a的地址是 :"<<std::hex<<std::showbase<<&a<<endl;
- cout<<"b的地址是 :"<<std::hex<<std::showbase<<&b<<endl;
- cout<<"f_1()的地址是 :"<<std::hex<<std::showbase<<f_1<<endl;
- cout<<"f_2()的地址是 :"<<std::hex<<std::showbase<<f_2<<endl;
- cout<<"main()的地址是 :"<<std::hex<<std::showbase<<main<<endl;
- cout<<"静态变量sa地址 :"<<std::hex<<std::showbase<<&sa<<endl;
- cout<<"静态变量sb地址 :"<<std::hex<<std::showbase<<&sb<<endl;
- cout<<"h1的地地址 :"<<std::hex<<std::showbase<<&h1<<endl;
- cout<<"h2的地址 :"<<std::hex<<std::showbase<<&h2<<endl;
- cout<<"new出来*h1地址:"<<std::hex<<std::showbase<<h1<<endl;
- cout<<"new出来*h2地址:"<<std::hex<<std::showbase<<h2<<endl;
- cin>>a;
- }
2.测试结果与布局图
运行结果:
内存分析:
全局变量,静态变量----存于数据区;
局部变量,函数形参----存于stack;
函数代码----------------存于代码区;
new出来的变量--------存于heap。
1.测试代码
- #include <iostream>
- #include <bitset>
- using namespace std;
- class CEmpty
- {
- };
- int main(int argc, char** argv)
- {
- CEmpty *pObjInHeap = new CEmpty();
- CEmpty objInStack;
- cout<<"CEmpty类型的对象占用内存大小(字节):"<<sizeof(CEmpty)<<endl;
- cout<<"堆上分配对象时,对象地址为:"<<std::hex<<std::showbase<<pObjInHeap<<endl;
- cout<<"栈上分配对象时,对象地址为:"<<std::hex<<std::showbase<<&objInStack<<endl;
- cout<<"堆上对象的内容是:"<<bitset<8>(*((char*)pObjInHeap))<<endl;
- cout<<"栈上对象的内容是: "<<bitset<8>(*((char*)(&objInStack)))<<endl;
- cin>>argc;
- }
2.运行结果与分析
可见:
(1)空类的对象也占有一个字节的内存空间,以证明自己的存在;
(2)对象既可以建立在stack上,也可以建立在heap上;
(3)这一个字节的值没有规定具体的值是多少。