如何判断new的内存是否失败?使用try catch

来源:互联网 发布:淘宝开通充值平台 编辑:程序博客网 时间:2024/05/17 02:28
#include<stdlib.h>#include<stdio.h>#include<exception>#include<iostream>#include<new>using namespace std;int main(){    try {        while(1)        {            //char *p = (char*)malloc(1000000*sizeof(char));            char *p = new char[1000000];            if(!p)                break;            else                printf("malloc 1M\n");        }        //free(p);    }catch(const bad_alloc& e)    {        cout<<e.what()<<endl;        cout<<"new exception\n";    }catch(const exception& e)    {        cout<<e.what();        cout<<"other exception\n";    }}

原创粉丝点击