0
class A
{
    public:
        static void * operator new (size_t,void *p) 
        {                                                           
            return p;
        }
        int i;
};


int main()
{
    void *p = malloc(sizeof(A));
    cout<<p<<endl;
    A *a= new (p) A;
    a->i = 10;
    cout<<a<<endl;
    cout<<a->i<<endl;
    a->i = 100;
    cout<<a->i<<endl;
}

output:

0x1e0e010
0x1e0e010
10
100

But I change the code of operator new to

static void * operator new (size_t,void *p) 
{                                                           
    return p+1024;
}

it doesn't crash and its output is:

0x25c4010
0x25c4410
10
100

I am using ubuntu13.10 and gcc4.8.1

Thanks

camino
  • 10,085
  • 20
  • 64
  • 115

1 Answers1

4

The short answer: Undefined behavior is undefined.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42