//class.h
class myclss
{
public:
int nvar;
double* savevar;
public:
myclss(){};
myclss(int var);
~myclss();
};
//class.cpp
#pragma once
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include "class.h"
#define new new(_CLIENT_BLOCK,__FILE__,__LINE__)
myclss::myclss(int var)
{
this->savevar=(double*)malloc(sizeof(double)*var);
}
myclss::~myclss()
{
if(!savevar)
{
free(savevar);
savevar=NULL;
}
}
//main.cpp
#pragma once
#include "class.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <assert.h>
#define new new( _CLIENT_BLOCK,__FILE__,__LINE__)
void Exit()
{
int i=_CrtDumpMemoryLeaks();
assert(i==0);
}
int main()
{
atexit(Exit);
myclss t(2);
//_CrtDumpMemoryLeaks();
return 0;
}
代码如上所示,我是自己定义一个类,在构造函数中为类对象分配内存,在析构函数中释放,结果仍然报内存没有释放,不知道是什么问题,请指教!
------解决方案--------------------------------------------------------
myclss::~myclss()
{
if(!savevar) 应该是 if (savevar),楼主手误啊
{
free(savevar);
savevar=NULL;
}
}