0

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

Community
  • 1
  • 1

4 Answers4

1

Yep it leaks. function doesn't actually modify the value of t in main (because it's parameter is passed by value).

You can often reference deleted memory, but it is a bug (and not reliable).

John3136
  • 28,809
  • 4
  • 51
  • 69
1

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

At the first, there are two mistakes in your code.

pointer is not value.

void function (cTest * test){
  delete test;
  std::cout<<test->m<<std::endl;
  test= new cTest(1.2);
}

test is not overwrited. probably, you expect to re-write pointer value, but it can't. If you want to do it, use pointer of pointer CTest** test to define argument. Or use return value to give a new pointer value.

#include <iostream>

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;
}

But this code's not good sense, I think.

mattn
  • 7,571
  • 30
  • 54
1

Yes, there is a leak and double delete of the firstly allocated object. 't' in main continues to point to the first object, as the pointer is not passed to function by reference or double pointer.

nanda
  • 804
  • 4
  • 8