J
Jeff0803
Guest
Here is a sample program.
#include <iostream>
using namespace std;
struct S {
int *p;
};
S x{ new int{0} };
void f()
{
S y{ x }; // "copy" x
*y.p = 1; // change y; affects x
*x.p = 2; // change x; affects y
delete y.p; // affects x and y
y.p = new int{ 3 }; // OK:change y;does not affect x
*x.p = 4; // ?
}
int main()
{
f();
return(0);
}
I expected an error occur at *x.p = 4 because x is copied to y, y.p is deleted and then new memory is allocated to it, and *x.p = 4 is trying to write to deallocated memory.
However there's no crash and *x.p and *y.p are both 4.
Can anybody explain this?
Continue reading...
#include <iostream>
using namespace std;
struct S {
int *p;
};
S x{ new int{0} };
void f()
{
S y{ x }; // "copy" x
*y.p = 1; // change y; affects x
*x.p = 2; // change x; affects y
delete y.p; // affects x and y
y.p = new int{ 3 }; // OK:change y;does not affect x
*x.p = 4; // ?
}
int main()
{
f();
return(0);
}
I expected an error occur at *x.p = 4 because x is copied to y, y.p is deleted and then new memory is allocated to it, and *x.p = 4 is trying to write to deallocated memory.
However there's no crash and *x.p and *y.p are both 4.
Can anybody explain this?
Continue reading...