https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70331

            Bug ID: 70331
           Summary: missing error dereferencing a dangling pointer in
                    constexpr function
           Product: gcc
           Version: 6.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

The constexpr function f in the test case below has well-defined behavior only
when its argument is non-zero.  When its argument is zero, the function returns
a value obtained by dereferencing a dangling pointer.  Since an expression with
undefined behavior is not a valid core constant expression it cannot be used to
initialize a constexpr variable and the whole program below should be rejected
with an error.  However, GCC accepts it without a diagnostic.

$ cat x.c && /build/gcc-trunk/gcc/xgcc -B /build/gcc-trunk/gcc -S -Wall -Wextra
-Wpedantic -o/dev/stdout -xc++ x.c
constexpr int f (int i)
{
    int *p = &i;
    if (i == 0) {
        int j = 123;
        p = &j;
    }

    return *p;
}

constexpr int i = f (0);
const int j = i;


For comparison, Clang produces the following output:

x.c:12:15: error: constexpr variable 'i' must be
      initialized by a constant expression
constexpr int i = f (0);
              ^   ~~~~~
x.c:9:12: note: read of object outside its
      lifetime is not allowed in a constant expression
    return *p;
           ^
x.c:12:19: note: in call to 'f(0)'
constexpr int i = f (0);
                  ^
1 error generated.

Reply via email to