| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 858 人关注过本帖
标题:关于异常处理和动态内存管理
只看楼主 加入收藏
北方七宿
Rank: 1
等 级:新手上路
帖 子:4
专家分:0
注 册:2008-6-28
收藏
 问题点数:0 回复次数:3 
关于异常处理和动态内存管理
以下程序,用来进行动态数组的内存异常管理,有颜色部分好像有问题,无论怎样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
搜索更多相关主题的帖子: 内存 动态 管理 
2008-07-04 23:38
Arcticanimal
Rank: 3Rank: 3
等 级:论坛游民
威 望:7
帖 子:341
专家分:20
注 册:2007-3-17
收藏
得分:0 
申请的空间被delete掉了之后指针的值并不会变, 所以, 你怎么知道没能释放内存 ?
n足够大new就会失败,申请内存不成功系统不会终止你的程序, 只是返回的指针为空.

try new catch
2008-07-05 15:23
missiyou
Rank: 5Rank: 5
等 级:贵宾
威 望:16
帖 子:531
专家分:218
注 册:2007-10-9
收藏
得分:0 
void Delete(int *&p)
{
    cout<<p<<endl;
    if(p==NULL) throw 1.1;
    delete []p;//还有这种删法吗,delete p[];应该这样吧
    cout<<p<<endl;
}
2008-07-06 11:40
北方七宿
Rank: 1
等 级:新手上路
帖 子:4
专家分:0
注 册:2008-6-28
收藏
得分:0 
问题解决
确实删除后指针所指的位置没有变化,但其中的数据已经释放。多谢了!
顺便说一下,我的释放内存语句没有错误,[]确实在前面。
2008-07-06 12:45
快速回复:关于异常处理和动态内存管理
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012020 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved