Aha*_*han 1 c++ memory arrays dynamic
我目前正在阅读C++ prime plus以学习动态内存分配.我在书上尝试了一段代码,但是在我添加了一行之后,我对所得到的内容感到困惑:在我释放p3的内存并且计算机实际打印出来后,我让计算机打印出p3 [2] p3的正确值.但是,在您释放内存后,它是不是不可能打印出来?
这是代码:
// arraynew.cpp -- using the new operator for arrays
#include <iostream>
int main() {
using namespace std;
double * p3 = new double [3]; // space for 3 doubles
p3[0] = 0.2; // treat p3 like an array name
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is " << p3[1] << ".\n";
p3 = p3 + 1; // increment the pointer
cout << "Now p3[0] is " << p3[0] << " and ";
cout << "p3[1] is " << p3[1] << ".\n";
cout << "p3[2] is " << p3[2] << ".\n";
p3 = p3 - 1; // point back to beginning
delete [] p3; // free the memory
cout << "p3[2] is " << p3[2] << ".\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
p3[1] is 0.5.
Now p3[0] is 0.5 and p3[1] is 0.8.
p3[2] is 6.95326e-310.
p3[2] is 0.8.
Run Code Online (Sandbox Code Playgroud)
取消分配内存后,内容将失效.这并不意味着必须删除它们 - 这将浪费操作系统的资源.解除分配通常意味着只要其他进程请求HEAP内存,操作系统就可以自由使用此内存 - 如果您尝试访问此内存,同时很可能会像您一样在那里找到原始内容.
也就是说,尝试访问已释放的内存是未定义的行为.您无法保证在那里找到原始内容,也不会立即删除它们.什么都可能发生,所以不要这样做!