首页 > 代码库 > C++的学习记录 - 01

C++的学习记录 - 01

动态内存分配和释放一直不怎么明白。

 

实验程序为:

 1 # include <iostream> 2 # include <cstdlib> 3 using namespace std; 4  5 int main() 6 { 7     int *p; 8     if((p = new int(5)) == 0) 9     {10         cout<<"can‘t allocate more memory, terminating.."<<endl;11         exit(1);12     }13     14     cout<<"Before deleting:"<<endl;15     cout<<"p = "<<p<<endl;16     cout<<"*p = "<<*p<<endl<<endl;17     18     delete p;19     20     cout<<"After deleting:"<<endl;21     cout<<"p = "<<p<<endl;22     cout<<"*p = "<<*p<<endl;23     24     return 0;25 }

程序结果为:

Before deleting:
p = 0x9724008
*p = 5

After deleting:
p = 0x9724008
*p = 0

堆内存被释放后,指针还指向原来的位置,内容改变为“0”。

 

为什么是0呢。。。。。。

C++的学习记录 - 01