简体   繁体   中英

Handle out of memory situation with static arrays memory C++

Is there a way to handle out of memory error when using an array that was initialized as static memory, like in the code given below?

namespace x{
static unsigned char arr[9999999]; // how to catch etc. if there is out of memory exception

};

There is no way of detecting that; your program will either crash. fail to load, or go off into UB land. Hopefully, if the size is completely ridiculous for your platform, your compiler will diagnose it at compile-time, but it doesn't have to.

When you compile and link an executable, code is included that performs the steps to create your global and static data structures before your program is ever called by way of your main() function. The construction of the array you are speaking of would occur prior to any of your code being executed, and would therefor result in a problem that would be uncatchable in your code, if catchable at all.

There is unlikely to be any out-of-memory problem with the given code. All it's going to do is to declare a rather big symbol, and generally, program behavior will be no different from just having a program which is too big to load into memory - the loader will complain. But the size of the sample is not big at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM