dimanche 21 octobre 2018

Why is the code failing in the Destructor?

I have gone through stackoverflow questions similar to "Why is the destructor called twice?". My question can be a similar one but with a small change. I am getting an error when running the following code:

#include<iostream>
#include<string>
using namespace std;

struct Employee{
char *name;
char *tag;
Employee *employee;

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

I debugged the code and found that error is raising when the destructor is called second time when the main function exits.

1) I want to know why the code fails to run?

2) Are there any memory leaks?

3) How can I fix the error properly deallocating memory?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire