C++ new operator return values

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

C++ new operator return values

Post by Neo »

What happens when 'new' is not able to allocate enough memory?
Does it return NULL like the alloc() functions or does it only throw an exception?
Only Human
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:C++ new operator return values

Post by Solar »

Default behaviour is to throw a bad_alloc exception. I've heard about certain settings you could make to change that behaviour to e.g. returning NULL, but haven't given them a try so far.

Note that most UNIXish operating systems will never throw such an exception, but return successfully at first (when they do the page table entries) and die violently later (when the page fault handler tries to actually allocate physical pages)...
Every good solution is obvious once you've found it.
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:C++ new operator return values

Post by Pype.Clicker »

Solar wrote: Note that most UNIXish operating systems will never throw such an exception, but return successfully at first (when they do the page table entries) and die violently later (when the page fault handler tries to actually allocate physical pages)...
So there's nothing catching the SIGSEGV and throwing a "bad_alloc" exception instead ??

this also reminds me of a rule-of-thumb i read somewhere about OOP:
"if you thing something might fail, don't do it in your constructor" ;)
distantvoices
Member
Member
Posts: 1600
Joined: Wed Oct 18, 2006 11:59 am
Location: Vienna/Austria
Contact:

Re:C++ new operator return values

Post by distantvoices »

@solar: don't unix-like systems create a virtual memory entry for the appended heap and map in the pages upon need (page fault handler doing the grunt work so to say)?
... the osdever formerly known as beyond infinity ...
BlueillusionOS iso image
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:C++ new operator return values

Post by Solar »

That's what I said. The actual out-of-(swap)-memory condition happens long after the (successful) malloc / new call.
Every good solution is obvious once you've found it.
Post Reply