C++内存分配异常处理

来源:互联网 发布:软件开发书籍 编辑:程序博客网 时间:2024/04/29 19:52

在内存分配失败的情况下,new会抛出bad_alloc的异常,而malloc会返回空指针

a. new异常处理
try { int* a = new int[8000000000];cout << "get memory" << endl; } catch(bad_alloc& ba) {cout << "catch the exception" << endl; }

b. malloc异常处理:
int* a = (int*)malloc(8000000000);if(NULL == a){cout << "alloc memory failed" << endl;}  

c. new也可以通过判断返回值处理异常
int* a = new(std::nothrow)int[8000000000];if(NULL == a){cout << "alloc memory failed" << endl;}  

原创粉丝点击