Search code examples
c++doublefreecorruption

Error : double free or corruption (fasttop)


I try since a few day to make this little code but it doesn't work. I see a lot of question about this problem but i didn't find an answer to mine.

Here is the code for Voiture.cpp :

#include <iostream>
using namespace std;
#include <string.h>
#include "modele.h"

Voiture::Voiture()
{
Nom=NULL;
setNom("Default");
VoitChoix=Modele();
cout << "COnstructeur default" << endl;
}

Voiture::Voiture(const char* N,const Modele V)
{
Nom=NULL;
setNom(N);
setModele(V);
cout << "COnstructeur initialisation" << endl;
}

Voiture::Voiture(const Voiture& V)
{
Nom=NULL;
setNom(V.getNom());
setModele(V.getModele());
cout << "COnstructeur copie" << endl;
}
Voiture::~Voiture()
{
if(Nom)
{
    cout << "Voiture : Destruction de" << Nom << endl;
    delete [] Nom;
}
}    

Here is the code for Modele.cpp :

#include <iostream>
#include <string.h>
using namespace std;
#include "modele.h"

Modele::Modele()
{
Nom=NULL;
setNom("Default");
Puissance=0;
Diesel=true;
PrixDeBase=0;
cout << "COnstructeur default" << endl;
}
Modele::Modele(const char* N,const int P,const bool D,const float PDB)
{
Nom=NULL;
setNom(N);
setPuissance(P);
setDiesel(D);
setPrixDeBase(PDB);
cout << "COnstructeur initialisation" << endl;
}
Modele::Modele(const Modele& M)
{
Nom=NULL;
setNom(M.getNom());
setPuissance(M.getPuissance());
setDiesel(M.isDiesel());
setPrixDeBase(M.getPrixDeBase());
cout << "COnstructeur copie" << endl;
}

Modele::~Modele()
{
if(Nom)
{
    cout << "Modele: Destruction de" << Nom << endl;
    delete [] Nom;
}
}

Here is the code for main.cpp :

int main()
{
cout << "(1) ***** Test du constructeur par defaut de Voiture *****" << endl;
{
Voiture voiture;
voiture.Affiche();
}
}

I don't put all the code, just where i have the problem.

Thanks ! :(


Solution

  • One obvious problem is that you're missing a user-defined assignment operator:

    VoitChoix=Modele();
    

    This calls the assignment operator, not copy constructor. Since you do not have a user-defined assignment operator for Modele, then you will have issues on destruction of VoitChoix. More specifically, you are assigning all of the values that Modele() has created to VoitChoix.

    So you have two instances that have the same pointer value for Nom. When the temporary Modele() goes out of scope, it will call the destructor, thus deleting Nom. When VoitChoix goes out of scope, it will attempt to delete the same pointer value for Nom. Thus the double delete error.

    The user defined assignment operator for Modele would have the following signature:

    Modele& operator=(const Modele&);
    

    You will need to implement this function before going any further. This can be done easily using the copy/swap idiom: What is the copy-and-swap idiom?

    Also, please follow the rule of three when creating your class: What is The Rule of Three?