1

I have made a application for high resolution images.

when I want to allocate large amount of memory, the system says "Application has requested the Runtime to terminate it in an unusual way." But what I want is, the allocated pointer must return 0 Or NULL that I can show my message. It does not return zero/NULL why ? any idea? I checked with debug, before proceeding to MessageBox, it gives this error. what to do here to display my message ?

And is there a way to check that the user is going to allocate large enough memory than the computer PC capacity ?

Thanks.

ImageW = 2000;
ImageH = 2000;
point *Img = NULL;
Img = new point[ImageW*ImageH];
if(Img== NULL)
{   
MessageBox(0, "Your computer memory is too small.", "Error", MB_ICONERROR | MB_OK);
return; 
}
maxpayne
  • 1,111
  • 2
  • 21
  • 41

3 Answers3

5

Unlike malloc in C which returns NULL on failure, new in C++ can throw a std::bad_alloc exception which is what you're seeing. See http://en.cppreference.com/w/cpp/memory/new/operator_new for reference

To handle this exception you can use try/catch:

try {
    Img = new point[ImageW*ImageH];
}
catch (std::bad_alloc const& e) {
    // handle failure here, like displaying a message
}

Here's documentation for the std::bad_alloc exception: http://en.cppreference.com/w/cpp/memory/new/bad_alloc

Alexander Kondratskiy
  • 4,156
  • 2
  • 30
  • 51
5

Use nothrow:

Img = new (nothrow) point[ImageW*ImageH];
//        ^^^^^^^^^^

Now you get a null pointer, rather than an exception, if the allocation failed.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

C++ "new" does not return null on failure, it calls the new handler.

Permaquid
  • 1,950
  • 1
  • 14
  • 15