[PATCH] Warn when NULL is returned from 'operator new' without 'throw()'

Artyom Skrobov Artyom.Skrobov at arm.com
Sat Jan 11 09:48:47 PST 2014

Thank you very much Richard!


Attaching the updated patch for your review




From: metafoo at gmail.com [mailto:metafoo at gmail.com] On Behalf Of Richard
Sent: 10 January 2014 23:25
To: Artyom Skrobov
Cc: cfe commits
Subject: Re: [PATCH] Warn when NULL is returned from 'operator new' without


On Fri, Jan 10, 2014 at 5:07 AM, Artyom Skrobov <Artyom.Skrobov at arm.com>

Thank you for your suggestions Richard!
One point though:

> Please use RetValExp->isNullPointerConstant instead.
> Please also add testcases for operator new returning nullptr, and
returning expressions such as 1 - 1, and for operator new marked as

I want to note that expressions such as 1-1 are invalid as return values
from operator new, and produce "error: cannot initialize return object of
type 'void *' with an rvalue of type 'int'"


Expressions such as 1 - 1 are valid null pointer constants in C++98 but not
in C++11.


At the same time, expressions such as (void*)(1-1) are not recognized either
by isNullPointerConstant or by EvaluateAsInt as integer zeroes, namely
because they are not integers.


In C++11, (void*)(1 - 1) is a reinterpret_cast of 0 to void*, and isn't
(necessarily) a null pointer. In C++98, it's a static_cast, and is a null


For a reference, GCC doesn't warn on

   void *operator new(size_t n) {
     return (void*)(1-1);

which isn't too bad; but neither does it warn on

   void *operator new(size_t n) {
     void* blah = 0;
     return blah;


OK, I would not expect a warning here.


nor even on

   void *operator new(size_t n) {
     return (void*)0;


I *would* expect a warning here.


which seems quite valuable to be able to detect.

isNullPointerConstant doesn't recognize the two latter cases as null pointer
constants, either.


Sorry for sending you in the wrong direction!


Do you think Clang should be able to detect such null-pointer-expressions?
If so, could you advise how it could be implemented, seeing that
isNullPointerConstant and EvaluateAsInt prove ineffective?


It looks like the best way to achieve this is to use
Expr::EvaluateAsBooleanCondition on the (converted) return expression. That
matches what we do for __attribute__((nonnull)).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20140111/351e8d51/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: operator-new-NULL.updated.patch
Type: application/octet-stream
Size: 6048 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20140111/351e8d51/attachment.obj>

More information about the cfe-commits mailing list