Operator New and Delete - Unnecessary Conditions

19:39
Fri
09
Dec 2016

Operator New and Delete - Unnecessary Conditions

I've seen following constructs many times in C++ code:

MyClass* obj = new MyClass();
if(obj == nullptr)
    // Handle allocation error.

// ...

if(obj != nullptr)
    delete obj;

Both of these conditions are unnecessary. Strictly speaking they are not a bug - program will run correctly, but they make no sense. If you used to write any of these, you should know that:

1. Operator new doesn't return null on failed allocation. By default it throws an exception of type std::bad_alloc in this case, so this is what you should handle if you really care about the state of your program after it runs out of memory (or if the allocated object is particularly big).

There is also special nothrow version of the new operator that returns null on failure, but you must call it explicitly. An alternative would be to overload new operator (global or for particular class) to change its behavior. But again, this is not what happens by default.

Note this is different behavior than malloc function from C. Obviously there are no exceptions in C language, so this function just returns null on failure.

2. Operator delete doesn't crash when you pass null pointer to it - it just does nothing, so the check for not-null is already inside, you don't have to write it. Of course trying to delete object from any non-null address that was already freed or is just invalid address still crashes, or causes other undefined behavior.

Note this is the same behavior as free function from C - it also accepts null pointer.

Comments (0) | Tags: c++ | Author: Adam Sawicki | Share

Comments

(No comments)

Post comment

Nick *
Your name or nickname
E-mail
Your contact information (optional, will not be shown)
Text *
Content of your comment
Calculate *
(* - required field)
STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2017 Adam Sawicki
Copyright © 2004-2017 Adam Sawicki