1

While experimenting with dynamic memory allocation using new, I discovered that is possible to request an amount of memory that is so large that the implementation doesn't throw a bad_alloc exception, but simply crashes with an invalid allocation error. I attempted testing the size of the allocation using a simple test to the effect

    if (n >= SIZE_MAX / sizeof(double)) 
        // throw some exception
    else 
        // try to allocate memory

where n is the number of doubles that I am attempting to allocate, but I discovered that requests that pass this test can still cause the program to crash. Is there a simple test that is portable that can determine if a request is safe?

Thank you for your time.

edit: I apologize, here is an example of a program that crashes on my system. I created the program using visual studio 2013.

#include <cstdint>
#include <new>

int main()
{
    size_t n = SIZE_MAX / sizeof(double);
    double* ptr;

    try {
        new double[n];
        } catch (std::bad_alloc& e){ };
 }
  • 1
    I´m pretty sure it shouldn´t crash. Did you try with a minimal example (ie. can you be sure there are no other errors hidden in your code => undef. behaviour & co)? Compiler, OS...? – deviantfan Sep 22 '14 at 00:27
  • Are you able to try with gcc in case it's a compiler bug? – Chris Hayes Sep 22 '14 at 00:43
  • I actually only have VS on this system. – Matthew Papageorge Sep 22 '14 at 00:47
  • possible duplicate of [Why am I getting "Invalid Allocation Size: 4294967295 Bytes" instead of an std::bad\_alloc exception?](http://stackoverflow.com/questions/23470003/why-am-i-getting-invalid-allocation-size-4294967295-bytes-instead-of-an-std). The accepted answer has what you're looking for. – Captain Obvlious Sep 22 '14 at 00:58
  • The accepted answer prescribes the same test that I mentioned in the initial question. In fact, that is exactly where I found the aforementioned test. The reason why I created a new question is because the test failed on my system. – Matthew Papageorge Sep 22 '14 at 01:06
  • The actual error is nothing more than a debug asset invoked by the debug version of the VS runtime. Click ignore or run a release build and you'll get your exception. If you are sourcing information from another question it's always a good idea to include a link to it. – Captain Obvlious Sep 22 '14 at 01:20
  • Thanks Captain Oblivious, that makes a lot of sense. – Matthew Papageorge Sep 22 '14 at 01:34

1 Answers1

0

I believe the reason you are running into this error is because you are trying to allocate 4GB of memory, in visual studio you will have a max size that you can allocate in total in your program, this value can be changed in the configuration. If you try running your program in release mode it should disappear as visual studio does not have the safe check in release.

Hope this helps

Sora
  • 21
  • 8