0

I have the following code, in which I dynamically allocate memory, and then it deletes it two times in the destructor, causing an error. How can I go about fixing this?

(Nothing wrong, see edit below).

class Song {
private:
    char *name;

public:
    Song (char *name = "") {
        this->name = new char[strlen(name)+1];
        this->name[strlen(name)] = '\0';
        strcpy(this->name, name);
    }
    ~Song() {
        cout << "DEST" << endl; // gets called 2 times, causing an error.
        delete [] this->name;
    }
};

class CD {
private:
    Song songs[1];

public:
    CD() {}

    ~CD() {}
};

int main() {
    CD cd1;
    
    Song song1("Song1");

    return 0;
}

Edit: It seems like this code doesn't actually have anything wrong.

The problem was in another part of my code: I used the = operator, but didn't have a copy assignment constructor. Thanks for your help suggesting the rule of three.

Quaei
  • 3
  • 5
  • 2
    You should see the destructor called twice. `cd1` has a `Song` inside it, and `song1` in main is a `Song`, so when both of those objects go out of scope, you should see two destructor calls. That said, you do have a [rule of three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) violation. – NathanOliver Mar 17 '21 at 21:44
  • You want to check out the [rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three) (3 in your case). Or make your life easier and use `std::string` instead of naked pointers. But this code doesn't have any errors. – Lukas-T Mar 17 '21 at 21:46

1 Answers1

0

It doesn't delete your char array two times, it creates two instancies of your class, so it allocates memory for two strings, then it deletes this memory at destructor. There isn't any double free in your code, what could be the source of your problem (but shouldn't crash your program) is that you assign a string litteral to a char* which is deprecated in c++, you should instead use a const char* in the prototype of your constructor Song (const char * name);

Fayeure
  • 1,181
  • 9
  • 21