new 内存异常及捕获demo
int main(){
int i=0;
for(;i<200000;i++){
char *p = new char[1000 * 1000 * 1000];
}
cout<<"i="<<i<<endl;
}
./b
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
[postgres@local ~]$ free -m
total used free shared buff/cache available
Mem: 1817 198 1544 11 75 1503
Swap: 2107 449 1658
[postgres@local ~]$ free -m
total used free shared buff/cache available
Mem: 1817 1364 377 11 74 336
Swap: 2107 960 1147
捕获异常代码
#include <cstdio> #include <iostream> using namespace std; #include <chrono> #include <thread> int main(){ int i=0; try{ for(;i<200000;i++){ char *p = new char[1000 * 1000 * 1000]; } } catch( bad_alloc &ba) { cout << ba.what( ) << endl; cout<<"sleep 2"<<endl; std::this_thread::sleep_for(std::chrono::seconds(2)); cout<<"i="<<i<<endl; }; } ./b std::bad_alloc sleep 2 i=140735

浙公网安备 33010602011771号