[Bug c++/94671] New: Wrong behavior with operator new overloading when using O2 for optimization

basv@odd-e.com gcc-bugzilla@gcc.gnu.org
Mon Apr 20 13:03:34 GMT 2020


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

            Bug ID: 94671
           Summary: Wrong behavior with operator new overloading when
                    using O2 for optimization
           Product: gcc
           Version: 10.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: basv@odd-e.com
  Target Milestone: ---

This bug is a similar bug as an earlier reported in clang:
https://bugs.llvm.org/show_bug.cgi?id=15541

When having the overloaded new operator defined in other cpp or in a lib, g++
with O2 optimizes a new operation without assignment (or assignment to local or
static), and it will not call the overloaded new at all.

The following code will reproduce the problem.

---------------
test.cpp:
---------------

#include <iostream>

#define CHECK(expect, actual) std::cout << "EXPECT:" << expect <<
"\tACTUAL:"<<actual << std::endl
extern bool newCalled;

void testNewWithoutAssignment() {
        newCalled = false;
        new char;
        CHECK(1, newCalled);
}

static char* somechar;
void testNewWithAssignmentToStatic() {
        newCalled = false;
        somechar = new char;
        CHECK(1, newCalled);
}


char *p;
void testNewWithAssignment() {
        newCalled = false;
        p = new char;
        CHECK(1, newCalled);
}

int main() {
        testNewWithoutAssignment();
        testNewWithAssignmentToStatic();
        testNewWithAssignment();
        return 0;
}

---------------
new.cpp:
---------------

#include <exception>
#include <new>
#include <cstdlib>

extern bool newCalled;
bool newCalled = false;
void* operator new (size_t size)  throw (std::bad_alloc)
{
        newCalled = true;
        return malloc(size);
}

-----------

I know this is an optimization (it doesn't happen with -O0)... but it does
break the C++ standard.


More information about the Gcc-bugs mailing list