2

So I'm currently looking into std::bad_alloc and its behavior, and there's something I don't understand.

This very simple snippet:

try { 
    char* p = new char[10000000000ul];
} catch(std::bad_alloc& e) {
    std::cout << "Caught a bad alloc" << std::endl;
}

works and doesn't throw on my MacBook with 8GB of RAM. If I understand correctly, after reading a bit about it), it shows OSX may totally accept to allocate this amount of memory as virtual memory, though it means a lot of paging problem, switching pages between RAM and HDD.

Now if I execute this on my iPad with 1GB of RAM in a simple iOS application, I get:

malloc: *** mach_vm_map(size=10000007168) failed (error code=3)

*** error: can't allocate region

*** set a breakpoint in malloc_error_break to debug

libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc

I assume iOS is not happy with that amount of memory and just refuse to allocate it. Then, I understand std::bad_alloc is a serious error, but what exactly can cause it not to be caught here?

I reckon answer may be iOS/OSX specific and that the behavior may vary on other OSes/devices.

Community
  • 1
  • 1
JBL
  • 12,588
  • 4
  • 53
  • 84
  • Is there any difference if you say `catch(const std::bad_alloc& e)`? – JWWalker Mar 23 '15 at 20:09
  • I didn't, will do tomorrow to check; – JBL Mar 23 '15 at 23:38
  • @JWWalker Nope, no difference. – JBL Mar 24 '15 at 09:04
  • I don't know why you can't catch `std::bad_alloc`. You are allocating > 9GB here. Something to keep in mind, is that desktops can and do paging automatically, but iOS does not. So you will never be able to allocate more than the physical RAM on iOS – yano May 31 '18 at 16:58

0 Answers0