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

            Bug ID: 101480
           Summary: Miscompiled code involving operator new
           Product: gcc
           Version: 11.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jens.maurer at gmx dot net
  Target Milestone: ---

The following test case works correctly with gcc 10.3 (with any of -O0, -O1, or
-O3) and works with gcc 11.1 with -O0, but the assertion at #2 fires with gcc
11.1 with -O1 (and above).

The problem is that setting the flag at #1 (inlined into "f" just before
calling "new") is not performed in the generated machine code, and the
assertion in "operator new" then fails.


#include <stdlib.h>
#include <assert.h>

static bool flag = false;

class C
{
  bool prev;

public:
  C() : prev(flag)
  {
    flag = true; // #1
  }

  ~C() {
    flag = prev;
  }
};

void* operator new(unsigned long size)
{
  assert(flag);  // #2
  return malloc(size);
}

void operator delete(void *p)
{
  free(p);
}

void g(int* p)
{
  delete p;
}

void f()
{
  int* p;
  {
    C c;
    p = new int;
  }
  g(p);
}

int main(int, char**)
{
  f();
}

Reply via email to