Checking null pointers from new Operator

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
rootel77

Checking null pointers from new Operator

Post by rootel77 »

Hi,

Last night, i had a problem with my c++ memory allocator test code. when there is no more memory to allocate the kernel throw a page fault exception (although i test the return value from the new operator). then i checked the generated asm code to see if the copmiler insert any check before calling the constructor, result: nothing, the compiler call directly the constructor.

I looked at some docs on the web. it seems the C++ standard stipulates that the new operator should throw a std::bad_alloc exception if the allocation fails unless it is declared throw() and called with an additional parameter nothrow (wich is not my case because i disable the exceptions).

fortunately, i found a command line optin in the gcc manual
-fcheck-new
Check that the pointer returned by operator new is non-null before attempting to modify the storage allocated. This check is normally unnecessary because the C++ standard specifies that operator new will only return 0 if it is declared `throw()', in which case the compiler will always check the return value even without this option. In all other cases, when operator new has a non-empty exception specification, memory exhaustion is signalled by throwing std::bad_alloc. See also `new (nothrow)'.
i turned on this option and checked the generated asm code. now all is correct and the compiler insert a test for the value returned by new then skips the constructor call code if this value is null.
Post Reply