帮我分析一下这个c++程序

来源:百度知道 编辑:UC知道 时间:2024/06/07 23:32:47
#include <iostream>
#include <string>

using namespace std;
void getName();
int main()
{
getName();
return 0;

}

void getName()
{

char *p=new char[10];
cin>>p;
cout<<p<<endl;
}

这个程序中,函数getname调用完,new分配的空间是否还存在?

存在 你要用delete去释放才是正确的做法

用于申请和注销堆空间。new和delete与malloc和free的区别:new和delete会调用构造和析构函数,而malloc和free则不会。如果耗尽内存,调用new会产生bad_alloc异常。在delete之后,内存空间被回收,但是指针的值不变,该指针变成悬垂指针(dangling pointer),应该把它立即置NULL。
int * pi = new int; //没有初始化
int * pi = new int(); //初始化为0
const对象的动态分配和回收:
const int * pci = new const int(1024);
delete pci;