加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C异常处理和内存动态分配

发布时间:2020-12-16 09:58:58 所属栏目:百科 来源:网络整理
导读:我正在学习C语言中的异常处理,以下是我尝试将其应用于动态分配内存的方法: #include iostreamusing namespace std;int main(){ const char * message[] = {"Dynamic memory allocation failed! "}; enum Error{ MEMORY }; int * arr,length; cout "Enter le
我正在学习C语言中的异常处理,以下是我尝试将其应用于动态分配内存的方法:

#include <iostream>

using namespace std;

int main()
{
    const char * message[] = {"Dynamic memory allocation failed! "};
    enum Error{
        MEMORY
    };

    int * arr,length;
    cout << "Enter length of array: " << endl;
    cin >> length;

    try{
        arr = new int[length];
        if(!arr){
            throw MEMORY;
        }
    }
    catch(Error e){
        cout << "Error!" << message[e];
    }
    delete [] arr;
}

它不能正常工作,如果我输入一些巨大的长度,而不是显示消息“动态内存分配失败!”(没有引号)我得到:

terminate called after throwing an instance of ‘std::bad_alloc’
what(): std::bad_alloc

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

Process returned 3 (0x3) execution time : 3.835 s
Press any key to continue.

任何的想法?

解决方法

运算符new本身会抛出错误.并且它的错误不是你指定的类型Error,所以如果无法分配内存,那么你的if语句将永远不会被执行,因为异常将被抛出.

您可以使用if删除块并尝试捕获由new运算符抛出的异常.或者使用std::nothrow

arr=new (std::nothrow)[length];

运算符分配内存

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读