关于异常处理和动态内存管理
[color=Blue]以下程序,用来进行动态数组的内存异常管理,有颜色部分好像有问题,无论怎样p都释放不掉,即使在主函数中加入绿色的一行来替换Delete函数也不行,这是怎么回事。还有,想故意让申请内存不成功要怎么办呢,貌似那样直接就被系统给中止了,那我编的处理函数要怎么才能被调用呢。[/color]#include<iostream>
using namespace std;
int* New(int n)
{
int *p;
if((p=new int[n])==NULL) throw 1;
return p;
}
[color=Red]void Delete(int *&p)
{
cout<<p<<endl;
if(p==NULL) throw 1.1;
delete []p;
cout<<p<<endl;
}[/color]int GetValue(int i,int a[],int n)
{
if(i<0) throw 'a';
if(i>n-1) throw "abc";
return a[i];
}
void main()
{
bool flag=true;
try
{
int *P,n,i;
cout<<"Input the number of the members."<<endl;
cin>>n;
P=New(n);
for(i=0;i<n;i++)
P[i]=i+1;
cout<<"Input the number of member that you want to know."<<endl;
cin>>i;
cout<<GetValue(i-1,P,n)<<endl;
cout<<P<<endl;
Delete(P);
[color=Green]delete []P;([/color][color=Green]注:此行与上一行二选一,都没能释放内存,请高手解释一下吧)[/color]
//Delete(P);
}
catch(int)
{
cout<<"申请内存失败"<<endl;
flag=false;
}
catch(double)
{
cout<<"内存释放错误"<<endl;
flag=false;
}
catch(char)
{
cout<<"数组应用超过下界"<<endl;
flag=false;
}
catch(char *)
{
cout<<"数组应用超过上界"<<endl;
flag=false;
}
if(flag==false) cout<<"程序有错误,请校验"<<endl;
else cout<<"运行成功!"<<endl;
cout<<"EXIT..."<<endl;
//cin>>flag;
}
运行结果:
Input the number of the members.
25
Input the number of member that you want to know.
10
10
00491C50
00491C50
运行成功!
EXIT...
Press any key to continue 申请的空间被delete掉了之后指针的值并不会变, 所以, 你怎么知道没能释放内存 ?
n足够大new就会失败,申请内存不成功系统不会终止你的程序, 只是返回的指针为空. void Delete(int *&p)
{
cout<<p<<endl;
if(p==NULL) throw 1.1;
delete []p;//还有这种删法吗,delete p[];应该这样吧
cout<<p<<endl;
}
问题解决
确实删除后指针所指的位置没有变化,但其中的数据已经释放。多谢了!顺便说一下,我的释放内存语句没有错误,[]确实在前面。
页:
[1]
