Optimization problem for overloaded class-specific new operators

Sebastian Bauer mail@sebastianbauer.info
Tue Feb 26 16:49:00 GMT 2019


I encountered a potential optimization problem with recent g++ versions 
that can be viewed with following code snipped (stripped down from a 
larger legacy code-base):


#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

struct OBJ {
     void *operator new (size_t size)
         void *p = malloc(size);
         memset(p, 0x1, size);
         return p;

     int a;

     OBJ() {

extern OBJ *oo;

int bug() {
     oo = new OBJ;
     return oo->a;


With gcc trunk and an optimization level of 1, bug() will not return 
0x01010101 (it will return an uninitialized/undefined value). Instead, 
the call to memset() is completely optimized out. I tried older versions 
as well, and it seems that the problem are starting to appear with gcc 6 
(so gcc 5 seems to be fine).

The various settings can be tried out here as well:


If I have not missed something then Clang and the VisualC compiler seem 
to produce the output that I would expect in this case.

Since this is a strange construct anyway, I'm not sure if this is just 
some undefined behaviour (in which gcc is right to optimize it out) or a 
real bug in gcc. Any suggestions (e.g., if a bug shall be reported or 
not) are appreciated.

Thanks a lot in advance!


More information about the Gcc-help mailing list