Search code examples
c++memoryoverflowmessage

How to avoid error messages in c++ caused by memory overflow


I have a C++ program which sometimes crashes because of memory overflow (max memory is 2GB, in some cases the program just needs more...).

I know that and I want the program to behave like that (because of reasons).

But the thing is, that windows opens a window with "Program stops working...".

How do I avoid these error messages and just get my application to shutdown without telling anything to the user?

Thanks in advance.


Solution

  • if you allocate memory using new you can try to catch std::bad_alloc exception

    try
    {
      buffer = new Type[HUGE_VAL];
    }
    catch (const std::bad_alloc& e)
    {
      gracefulExit();
    }
    

    Remember, that try & catch can be somewhere at top level (in main for example), while allocation itself deep inside processing etc.

    Still, reconsider doing your task in different way - split it into smaller tasks, or use some temporary files etc.