f******y 发帖数: 2971 | 1 In the following program, obviously there is a memory leak. Other than that,
I see memory newed in the main function is deleted twice. When I ran it, it
did not crash however. Anybody can explain it? Thanks
#include
class Ctest {
public:
Ctest(){}
~Ctest(){}
double m_value[200];
};
void function(Ctest* test) {
delete test;
test = new Ctest();
}
int main() {
Ctest* t = new Ctest();
function(t);
delete t;
return 0; | r****t 发帖数: 10904 | 2 你 new 了两次, delete 了两次吧
that,
it
【在 f******y 的大作中提到】 : In the following program, obviously there is a memory leak. Other than that, : I see memory newed in the main function is deleted twice. When I ran it, it : did not crash however. Anybody can explain it? Thanks : #include : class Ctest { : public: : Ctest(){} : ~Ctest(){} : double m_value[200]; : };
| t****t 发帖数: 6806 | 3 it is deleted twice, since the memory allocated in function() did not get re
turned.
so it is undefined behaviour. quite often it will lead to program crash. but
quite as often it will not lead to crash. thus it is undefined.
【在 r****t 的大作中提到】 : 你 new 了两次, delete 了两次吧 : : that, : it
| z****e 发帖数: 2024 | 4 void function(Ctest*& test)
这样才行。
【在 r****t 的大作中提到】 : 你 new 了两次, delete 了两次吧 : : that, : it
| r****t 发帖数: 10904 | | d*****d 发帖数: 46 | 6 interesting, try this
void function(Ctest* test) {
delete test;
Ctest* test1 = new Ctest();
test = new Ctest();
delete test1;
}
you may see why...
that,
it
【在 f******y 的大作中提到】 : In the following program, obviously there is a memory leak. Other than that, : I see memory newed in the main function is deleted twice. When I ran it, it : did not crash however. Anybody can explain it? Thanks : #include : class Ctest { : public: : Ctest(){} : ~Ctest(){} : double m_value[200]; : };
|
|