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

            Bug ID: 111773
           Summary: Inconsistent optimization of replaced operator new()
           Product: gcc
           Version: 13.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: vlad at solidsands dot nl
  Target Milestone: ---

#include <new>
#include <cstdint>
#include <cstdio>

int a[10];
void* operator new(std::size_t) {
    return a;
}

int main() {
    int* p = static_cast<int*>(::operator new(sizeof(int)));

    std::ptrdiff_t x = a - p;

    printf("%ld %d", x, x == 0);

    return 0;
}


Here, GCC with -O1 optimizes 'x' to 0 and 'x == 0' to false at the same time.

Compiler explorer link: https://godbolt.org/z/4Y3eeY56r

---
Also, possibly related:

#include <new>

void* operator new(std::size_t sz)
{
    throw std::bad_alloc{};
}

int main()
{
    int* p1 = static_cast<int*>(::operator new(sizeof(int)));

    return 10;
}

Here, again with -O1, terminate is not called, and the program returned
successfully. However, the program returned 0 instead of 10.

Compiler explorer link: https://godbolt.org/z/9oczTzP7s

Reply via email to