jeudi 4 novembre 2021

I cannout out why I get the error "core dumped" C++ [duplicate]

I don't know why when I run this piece of code :

#include <iostream>
#include <cstring>

class Masina{
    private:
        long long putere;
        int viteza;
        double masa; 
        bool calificativ; 
        char* nume;
    public:
        Masina();//constuctor default
        Masina(long long putere,int viteza,double masa,bool calificativ,char* nume);//constructor supraincarcat
        ~Masina();//destructor
    //  Masina(const Masina&) = delete;
    //  setter-e
        void setPutere(long long putere);
        void setViteza(int viteza);
        void setMasa(double masa);
        void setCalificativ(bool calificativ);
        void setNume(const char* nume);
    //  getter-e
        long long getPutere() const;
        int getViteza() const;
        double getMasa() const;
        bool getCalificativ() const;
        char* getNume() const;
};
//definire metode:
//constructor default
Masina::Masina():
    putere(2000), viteza(250), masa(1.5), calificativ(false),nume((char*)"o_marca")
{}
//constructor supraincarcat
Masina::Masina(long long putere,int viteza,double masa,bool calificativ,char* nume):
    putere(putere), viteza(viteza),masa(masa),calificativ(calificativ)
{}
//destructor default
Masina::~Masina()
{
    std::cout << "putere: "<<putere<<"\nviteza: "<<viteza<<"\nmasa: "<<masa<<"\ncalificativ: "<<calificativ<<"\nnume: "<<nume;
    std::cout<<"\nobiectul a fost sters\n\n";
}
//setter-e
void Masina::setPutere(long long putere)
{
    this->putere = putere;
}
void Masina::setViteza(int viteza)
{
    this->viteza = viteza;
}
void Masina::setMasa(double masa)
{
    this->masa = masa;
}
void Masina::setCalificativ(bool calificativ)
{
    this->calificativ = calificativ;
}
void Masina::setNume(const char* nume)
{
    strcpy(this->nume,(char*)nume);
}
//setter-e
long long Masina::getPutere() const
{
    return putere;
}
int Masina::getViteza() const
{
    return viteza;
}
double Masina::getMasa() const
{
    return masa;
}
bool Masina::getCalificativ() const
{
    return calificativ;
}
char* Masina::getNume() const
{
    return nume;
}

int main(){
    Masina* m1 = new Masina();
    {
        Masina m2 = *m1;
        m2.setNume("o_barca");
    }
    delete m1;
    return 0;
}

a segmentation fault occurs. As long as the copy constructor is not deleted I suppose that m2 should be a shallow copy of m1, thus, both char* nume keep the same value (pointing to the very same memory location). Thus, I expect that a change of the string stored at the address pointed by char * nume should change the content of both m1's and m2's string stored at char*nume.

Aucun commentaire:

Enregistrer un commentaire