根据Valgrind的临时std :: string泄漏的std :: shared_ptr?

时间:2014-02-16 07:51:34

标签: c++ memory-leaks valgrind shared-ptr

Valgrind告诉我这条线绝对泄漏。

std::shared_ptr<std::string> pName(new string);

但我看不出怎么样。谁能帮我吗?我仍然掌握着C ++。

这是Valgrind错误:

==14376== 313 (120 direct, 193 indirect) bytes in 5 blocks are definitely lost in loss record 3 of 3
==14376==    at 0x4C2A879: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14376==    by 0x40429D: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::__shared_count<std::string*>(std::string*) (shared_ptr_base.h:452)
==14376==    by 0x403DB7: std::__shared_ptr<std::string, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::string>(std::string*) (shared_ptr_base.h:768)
==14376==    by 0x40371C: std::shared_ptr<std::string>::shared_ptr<std::string>(std::string*) (shared_ptr.h:113)
==14376==    by 0x402145: sportsball::playBall(std::string, unsigned long, unsigned long) (sportsball.cpp:101)
==14376==    by 0x402AA3: main (sportsball.cpp:215)

如果您需要更多详细信息/背景,请在评论中告诉我。谢谢!

编辑:所以,更多细节......我正在创建shared_ptr<string>以放入PriorityQueue我已经实施的练习。

您可以查看整个项目here。以下代码位于sportsball.cpp

以下是直接背景:

PriorityQueue<shared_ptr<string> >* playerQueue = 
    new PriorityQueue<shared_ptr<string> >(initialCapacity, stepSize);
string line, priorityString;
int priority = 0;
int lineNumber = 0;
istringstream* lineStream = new istringstream();    

// For each line in the file
while (getline(infile, line)) {
//...

   lineStream->str(line); // replace the current string
   lineStream->clear(); // reset flags

   std::shared_ptr<std::string> pName(new string);

   // We can use getLine to parse up to our delimiter
   getline(*lineStream, *pName, INLINE_DELIMITER);
   // Then extract the rest of the line normally
   getline(*lineStream, priorityString);

   // Attempt to convert `priorityString` to an int
   // (we catch exceptions further down)
   priority = stoi(priorityString);

   if(sportsball::DEBUG) {
      cout << "Inserting " << *pName << "/"
           << priority << "." << endl;
   }

   // Cool. That worked. Now queue the player.
   playerQueue->insert(pName, priority);

   // probably not necessary
   pName.reset();
   priorityString.clear();

   //...
}

// Cleanup
delete lineStream;
delete playerQueue;

Edit2(已解决):事实证明,问题出在我的PriorityQueue.h文件中。 Valgrind错误有点误导。我错误地使用了std::allocator。当使用分配器来销毁先前分配的数组中的项时,必须为allocator.destroy(myArray+i)调用0 <= i < arraySize,而不是仅在第一个元素(allocator.destroy(myArray))上调用它。感谢@WhozCraig在评论中指出这一点。

0 个答案:

没有答案