Skip to content

[Clang] Insufficient diagnostics for dereferencing a null pointer in constant evaluation #77186

@frederick-vs-ja

Description

@frederick-vs-ja

Not sure whether there should be a separated issue, as it may be desired to track this as CWG2823.

Currently Clang accepts this program with warnings (Godbolt link):

static_assert([](int&) { return true; }(*static_cast<int*>(nullptr)));
static_assert(([]() -> int& { return *static_cast<int*>(nullptr); }(), true));

int main() {}
<source>:2:38: warning: binding dereferenced null pointer to reference has undefined behavior [-Wnull-dereference]
    2 | static_assert(([]() -> int& { return *static_cast<int*>(nullptr); }(), true));
      |                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~

The first line should also be diagnosed.

Also, it seems that dereferencing a null pointer should be an error in constant evaluation instead of a warning. In the following program, Clang doesn't make the constant evaluation fail due to this kind of UB and thus selects the first overload, which is wrong. Godbolt link.

#include <type_traits>

template<class T, bool = ([]() -> T& { return *static_cast<T*>(nullptr); }(), true)>
std::true_type fun(int);
template<class T>
std::false_type fun(...);

static_assert(!decltype(fun<int>(0))::value);

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions