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

Richard Smith richard at metafoo.co.uk
Fri Jan 10 15:25:23 PST 2014


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

> 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
> 'noexcept'.
>
> 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
pointer.


> 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/20140110/e0f2b7ec/attachment.html>


More information about the cfe-commits mailing list