C++中的内存泄漏以及如何修复它

memory leak in c++ and how to fix it

我收到内存泄漏错误, 我知道我必须取消分配内存,但该怎么做 我收到内存泄漏错误, 我知道我必须取消分配内存,但如何操作请指导

SongCollection::SongCollection(char* filename) {
 try {
  std::ifstream file("songs.txt");
  if (file) {
   while (file) {
    std::string temp, t_artist, t_title, t_album, t_price, t_year, t_length;
    std::getline(file, temp, '\n'); 
    if (!(temp.length() < 25)) {
     t_title = temp.substr(0, 25); 
     t_artist = temp.substr(25, 25); 
     t_album = temp.substr(50, 25); 
     t_year = temp.substr(75, 5); 
     t_length = temp.substr(80, 5); 
     t_price = temp.substr(85, 5);
     auto strip = [&](std::string& str) { 
      str = str.substr(str.find_first_not_of(" "), str.find_last_not_of(" ") + 1); 
      str = str.substr(0, str.find_last_not_of(" ") + 1); 
     };
     strip(t_title); 
     strip(t_artist); 
     strip(t_album);
     m_storage = new Song;
     m_storage->m_title = t_title;
     m_storage->m_artist = t_artist;
     m_storage->m_album = t_album;
     try {
      m_storage->m_year = std::stoi(t_year);
     }
     catch (...) {
      m_storage->m_year = 0;
     }
     m_storage->m_length = std::stoi(t_length);
     m_storage->m_price = std::stod(t_price);
     collection.push_back(m_storage);
    }
   }
  }
  else {
   throw 1;
  }
 }
 catch (int& err) {
  std::cerr << "ERROR: Cannot open file [" << filename << "].\n";
  exit(err);
 }
}

SongCollection::~SongCollection() {
 if (m_storage) {
  delete m_storage;
  m_storage = nullptr;
 }
 collection.clear();
}

我收到了这份内存泄漏报告

==141379== 2,345 (2,128 direct, 217 indirect) bytes in 19 blocks are definitely lost in loss record 3 of 3 
==141379==    at 0x4C2A593: operator new(unsigned long) (vg_replace_malloc.c:344) 
==141379==    by 0x403991: sdds::SongCollection::SongCollection(char*) (SongCollection.cpp:34) 
==141379==    by 0x402856: main (w7_p2_prof.cpp:29)

“最佳”™ 解决方案是根本不使用指针,因为这样就没有您可以忘记删除的动态分配。

对于您的情况,它包含一些相当小的更改以使其正常工作。

首先,我建议您创建一个 Song 构造函数,将所有需要的值作为参数,然后创建 Song 对象变得更容易:

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)
{
}

然后在你的 SongCollection class 中使用 Song objects 的向量而不是指针:

std::vector<Song> collection;

然后在一次性创建对象的同时将歌曲添加到向量中:

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

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

最后删除 SongCollection 析构函数。

没有指针,没有(明确的)动态分配,没有内存泄漏。并且没有破the rules of three/five,遵循零的规则。