Possible Duplicate:
C++ delete – It deletes my objects but I can still access the data?
I would like to check if the following simple code has memory leak. In the function, it deletes a pointer and assigns a new object to this pointer. Is this legal? Under g++ compiler, even I deletes the test pointer, I can still access its member, which looks weird for me.
class cTest{
public:
cTest(double _m){
m=_m;
}
~cTest(){}
double m;
};
void function (cTest * test){
delete test;
std::cout<<test->m<<std::endl;
test= new cTest(1.2);
}
int main(){
cTest *t = new cTest(0.1);
std::cout<<t->m<<std::endl;
function (t);
std::cout<<t->m<<std::endl;
delete t;
return 0;
}
it prints out
0.1
0.1
1.2
Whenever you access a pointer after its lifetime has ended (eg. stack allocated object or after a
delete) you stumble into undefined behavior, which is even worse than just an error because it may work and suddenly crash just when it decides to.The pointer is not valid anymore, data is still there because every unnecessary operation is not done in C++, that’s why in your situation it works.