Class 为什么代码在析构函数中失败?
我遇到过类似于“为什么析构函数调用了两次?”的stackoverflow问题。我的问题可以是一个类似的问题,但有一点变化。运行以下代码时出现错误:Class 为什么代码在析构函数中失败?,class,c++11,memory-management,memory-leaks,structure,Class,C++11,Memory Management,Memory Leaks,Structure,我遇到过类似于“为什么析构函数调用了两次?”的stackoverflow问题。我的问题可以是一个类似的问题,但有一点变化。运行以下代码时出现错误: struct Employee{ char *name; char *tag; Employee *employee; Employee(){ name = NULL; tag = NULL; employee =
struct Employee{
char *name;
char *tag;
Employee *employee;
Employee(){
name = NULL;
tag = NULL;
employee = NULL;
}
//copy constructor
Employee(const Employee &obj){
cout << "Copy constructor called" << endl;
name = (char*)malloc(sizeof(char)*strlen(obj.name));
strcpy(name, obj.name);
tag = (char*)malloc(sizeof(char)*strlen(obj.tag));
strcpy(tag, obj.tag);
employee = (struct Employee*)malloc(sizeof(obj.employee));
employee = obj.employee;
}
//overloaded assignment operator
void operator = (const Employee &obj){
cout << "Assignment operator called" << endl;
if (this == &obj){
return;
}
strcpy(name, obj.name);
strcpy(tag, obj.tag);
employee = obj.employee;
}
//destructor
~Employee(){
cout << "Destructor called" << endl;
if (name != NULL){
cout << "Freeing name" << endl;
free(name);
name = NULL;
}
if (tag != NULL){
cout << "Freeing tag" << endl;
free(tag);
tag = NULL;
}
if (employee != NULL){
cout << "Freeing employee" << endl;
free(employee);
employee = NULL;
}
}
};
Employee createNode(){
Employee emp;
emp.name = (char*)malloc(sizeof(char)* 25);
strcpy(emp.name, "Alan");
emp.tag = (char*)malloc(sizeof(char)* 25);
strcpy(emp.tag, "Engineer");
emp.employee = (struct Employee*)malloc(sizeof(struct Employee));//just created memory, no initialization
return emp;
}
Employee get(){
//Employee emp = createNode();
//return emp;
return createNode();
}
int main(){
Employee emp = get();
getchar();
return 0;
}
struct Employee{
字符*名称;
字符*标签;
雇员*雇员;
雇员(){
name=NULL;
tag=NULL;
employee=NULL;
}
//复制构造函数
员工(康斯特员工和obj){
cout您的问题是类中缺少复制构造和赋值运算符。因此,您多次释放类中的字符串。您的问题是类中缺少复制构造和赋值运算符。因此,您多次释放类中的字符串。刚刚尝试了您的代码d发现了导致崩溃的几个问题:
1) strlen返回不带空终止符的字符串长度,但是strcpy需要额外的字节,因此您的分配应该如下所示:
name = (char*)malloc(strlen(obj.name)+1);
2) 当您复制员工时,您复制了指针,因此内存泄漏,员工指针作为悬空指针
此外,malloc不能与构造函数一起工作,因此
employee = (struct Employee*)malloc(sizeof(obj.employee));
员工内部有垃圾。刚刚尝试了您的代码,发现了一些导致崩溃的问题:
1) strlen返回不带空终止符的字符串长度,但是strcpy需要额外的字节,因此您的分配应该如下所示:
name = (char*)malloc(strlen(obj.name)+1);
2) 当您复制员工时,您复制了指针,因此内存泄漏,员工指针作为悬空指针
此外,malloc不能与构造函数一起工作,因此
employee = (struct Employee*)malloc(sizeof(obj.employee));
<强>雇员< /String >内部有一个垃圾。阅读关于删除的不相关标签。努力理解为什么您甚至会有一个指针指向代码<雇员/>代码>作为代码>雇员Eng/C>的成员。这看起来不像一个链表。而这是C++,为什么<代码>名称<代码>和代码>标签>代码>不是<代码> STD::String < /C>看起来也很奇怪。对于名称和标记,我使用的是“名称空间std”,而不是“std::string”我现在使用一个指针C++作为一个结构成员,为了将来的目的。现在我只是在分配内存。读取关于删除的无关标签。很难理解为什么你甚至会有一个指针指向<代码>雇员>代码>作为代码>雇员Eng/C>的成员。这看起来不像一个链表。me
和标记
不是std::string
似乎也很奇怪。对于名称和标记,我使用“namespace std”而不是“std::string”。我使用指向Employee的指针作为结构成员,以备将来使用。现在我只分配内存。