关于异常处理和动态内存管理
以下程序,用来进行动态数组的内存异常管理,有颜色部分好像有问题,无论怎样p都释放不掉,即使在主函数中加入绿色的一行来替换Delete函数也不行,这是怎么回事。还有,想故意让申请内存不成功要怎么办呢,貌似那样直接就被系统给中止了,那我编的处理函数要怎么才能被调用呢。#include<iostream>
using namespace std;
int* New(int n)
{
int *p;
if((p=new int[n])==NULL) throw 1;
return p;
}
void Delete(int *&p)
{
cout<<p<<endl;
if(p==NULL) throw 1.1;
delete []p;
cout<<p<<endl;
}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);
delete []P;(注:此行与上一行二选一,都没能释放内存,请高手解释一下吧)
//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