mardi 28 juillet 2020

Double free or corruption (fasttop) error when trying to use setter

I have created a basic class object with setter and getters based on the text book. The code work fine but when I attempt to change the data in name from Square to Circle, I get error : double free or corruption (fasttop).

Can someone enlighten me what is happening here? Is this due to some kind of memory allocation error?

Below is a reproducible code:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Shape
{
    protected:
        string name;
        bool contains = false;
        
    public:
        Shape(string name, bool contains)
        {
            setName(name);
            setContains(contains);
        }
        
        string getName();
        bool getContains();
        string setName(string name);
        bool setContains(bool contains);
};

string Shape :: setName(string inputName)
{
    name = inputName;
}

bool Shape :: setContains(bool inputContains)
{
    contains = inputContains;
}

string Shape :: getName()
{
    return name;
}

bool Shape :: getContains()
{
    return contains;
}

int main()
{
    Shape object1("Square", true);
    cout << "Testing" << endl;
    cout << object1.getName() << endl;
    cout << object1.getContains() << endl;

    object1.setName("Circle");
    cout << object1.getName() << endl;
    return 0;
}

Edit:

Interesting, when running the code in OnlineGDB without object1.setName("Circle"); and cout << object1.getName() << endl; will report a segmentation fault error. What is the way to tackle this issue?

Aucun commentaire:

Enregistrer un commentaire