为什么delete指针成员变量后程序运行出错?
fatherclass类:
class fatherclass
{
public:
char *m_mychar;
public:
fatherclass();
fatherclass(char *ch);
virtual char *coutmychar() = 0;
virtual ~fatherclass();
};
fatherclass::fatherclass()
{
m_mychar = new char[16];
m_mychar = NULL;
cout < < "fatherclass is constructed " < <endl;
}
fatherclass::fatherclass(char *ch)
{
m_mychar = new char[16];
memcpy(m_mychar,ch,16);
cout < < "fatherclass is constructed ,get string " < <this-> m_mychar < <endl;
}
fatherclass::~fatherclass()
{
delete [] m_mychar;
}
sonclass类:
class sonclass : public fatherclass
{
public:
sonclass();
virtual ~sonclass();
char *coutmychar();
};
sonclass::sonclass()
{
}
sonclass::~sonclass()
{
}
char *sonclass::coutmychar()
{
cout < < "that is my char : " < <this-> m_mychar < <endl;
return this-> m_mychar;
}
主函数:
int main(int argc, char* argv[])
{
sonclass sc;
sc.m_mychar = "hahahahahaha ";
sc.coutmychar();
return 0;
}
编译过了,但程序运行时出错,大侠们可以帮小弟找出错误吗?十分感谢..
[解决办法]
//1.给sonclass加一个构造函数sonclass(const char* ch);
//2. fatherclass::fatherclass()中分配了内存再置为NULL, 是错误的.
//3. main中, 直接给sonclass.m_mychar赋字符串是错误的.
//修改如下:
#include <iostream>
#include <cstring>
using namespace std;
class fatherclass
{
public:
char *m_mychar;
public:
fatherclass();
fatherclass(const char *ch);
virtual char *coutmychar() = 0;
virtual ~fatherclass();
};
fatherclass::fatherclass()
{
m_mychar = NULL;
cout < < "fatherclass is constructed " < <endl;
}
fatherclass::fatherclass(const char *ch)
{
m_mychar = new char[strlen(ch)+1];
strcpy(m_mychar,ch);
cout < < "fatherclass is constructed ,get string " < <this-> m_mychar < <endl;
}
fatherclass::~fatherclass()
{
delete [] m_mychar;
}
//sonclass类:
class sonclass : public fatherclass
{
public:
sonclass();
sonclass(const char* ch);
virtual ~sonclass();
char *coutmychar();
};
sonclass::sonclass()
{
}
sonclass::sonclass(const char* ch)
:fatherclass(ch)
{
}
sonclass::~sonclass()
{
}
char *sonclass::coutmychar()
{
cout < < "that is my char : " < <this-> m_mychar < <endl;
return this-> m_mychar;
}
//主函数:
int main(int argc, char* argv[])
{
sonclass sc( "hahahahahaha ");
sc.coutmychar();
return 0;
}
[解决办法]
你出错的根本原因在这句话:
sc.m_mychar = "hahahahahaha ";
执行后sc中的m_mychar保存的是 "hahahahahaha ";这个字符串的内存地址,而不再是以前的了,而这个地址不是堆上的,你delete []m_mychar当然出错了,
另外,你这个程序还有内存泄漏,
main中的第一条语句sonclass sc;将导致
fatherclass::fatherclass()
{
m_mychar = new char[16];
m_mychar = NULL;
cout < < "fatherclass is constructed " < <endl;
}
上面这个函数运行,很明显m_mychar = new char[16];分配了内存,m_mychar = NULL;你又把这个内存给弄丢了,最法delete掉
[解决办法]
楼主,1、m_mychar = new char[16];
m_mychar = NULL; new 的空间明显成了野指针,不知道为什么要这样写
2、就算你没有m_mychar = NULL,你将sc.m_mychar = "hahahahahaha "; 相当于你把m_mychar指到另外一段空间,而这个空间不是new的,你原来的那个指针内存泄露。
