[Solved] memory leak in c++ and how to fix it


The “best”™ solution is to not use pointers at all, as then there’s no dynamic allocation that you can forget to delete.

For your case it includes a few rather minor changes to make it work.

First of all I recommend you create a Song constructor taking all needed values as arguments, then it becomes easier to create Song objects:

Song::Song(std::string const& title, std::string const& artist, std::string const& album, unsigned year)
    : m_title(title), m_artist(artist), m_album(album), m_year(year)
{
}

Then inside your SongCollection class use a vector of Song objects instead of pointers:

std::vector<Song> collection;

Then add songs to the vector while creating the objects all in one go:

 try {
  t_year = std::stoi(t_year);
 }
 catch (...) {
  t_year = 0;
 }

 collection.emplace_back(t_title, t_artist, t_album, t_year);

And finally remove the SongCollection destructor.

No pointers, no (explicit) dynamic allocation, no memory leaks. And no breaking the rules of three/five, by following the rule of zero.

solved memory leak in c++ and how to fix it