您的位置:首页 > 编程语言 > C语言/C++

how to catch out of memory exception in c++

2017-07-18 00:00 756 查看
to properly handle an out-of-memory scenario, you need to set aside some memory so that you can print an error message before exiting. Otherwise, the program will just crash on an unhandled exception while trying to print the error message. To do so, you can allocate a block of memory that is deallocated in the exception handler

// Reserve 16K of memory that can be deleted just in case we run out of memory
char* _emergencyMemory = new char[16384];
// ...
try {
// ...
} catch(bad_alloc ex) {
// Delete the reserved memory so we can print an error message before exiting
delete[] _emergencyMemory;

cerr << sizeof(int) * i << " bytes: Out of memory!";
cin.get();
exit(1);
}
//...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐