簡體   English   中英

在C / C ++中,鏈表僅在堆棧中分配了頭指針,而在堆中分配了其他節點。 這可能會導致內存泄漏嗎?

[英]In C/C++, linked list has only head pointer allocated in stack and other nodes allocated in heap. This may cause memory leak?

對於C和C ++,鏈表的指針指向其頭節點。 但是,所有節點都是通過malloc()或new分配在堆上的。 當頭指針超出其范圍(例如,其函數退出)時,分配在堆上的所有節點都將丟失。 對? 這是內存泄漏嗎?

C / C ++如何處理此類問題? 它會自動調用deallocator嗎? (例如free()或delete)?

處理此類問題的更好方法是使用標准容器,而不是一些自制的容器,除非您有充分的理由並知道您在做什么,以及為什么...

std :: vector <>
std :: list <>

但是要選擇一個容器,重要的是要知道您在做什么,壽命應該是什么。

@Jack-無論您做什么,標准容器都不會神奇地為您分配手動分配的對象。 從根本上講這是不可能的。

您必須更改解決問題的方法,才能將問題視為“手動分配的對象”。 一旦實現了這一飛躍,並且意識到這是一個糟糕的路要走,那么就可以在“它們是價值對象”或“它們將由shared_ptr管理”之間進行選擇。

EX1:使用shared_ptr來保存新對象(如果在MyNode上進行復制不是一個好主意[性能,擁有的資源,保留的狀態],則使用此方法):

void MyFunction()
{
  typedef boost::shared_ptr<MyNode> NodePtr;
  std::list<NodePtr> my_list;
  my_list.push_back(NodePtr(new MyNode(args...)));
  my_list.push_back(NodePtr(new MyNode(args...)));
  ...
  // when this function exits, the nodes, which are owned by shared_ptr's
  // which are themselves owned by a stack instance of std::list<> 
  // will be automatically deleted, no leaks anywhere...
}

EX2:如果您的節點很便宜,可以將其視為可復制對象(值語義),這是您要執行的操作:

void MyFunction()
{
  std::vector<MyNode> my_list;
  my_list.push_back(MyNode(args...));
  my_list.push_back(MyNode(args...));
  ...
  // when this function exits, the nodes, which are shored directly as copies
  // in the vector container, will be automatically deleted, no leaks anywhere...
}

而且,如果您出於某種原因確實希望手動管理實例(通常這樣做是因為生命周期並沒有真正與單個容器的生命周期相關聯,而是有一些不規則的生命周期,除了自定義算法以外,其他任何事物都不能將其整齊地封裝):

void MyFunction()
{
  std::list<MyNode*> my_list;
  my_list.push_back(new MyNode(args...));
  my_list.push_back(new MyNode(args...));
  ...
  // we must manually deallocate the nodes because nothing else has been given
  // responsibility anywhere (we're manually managing them)
  typedef std::list<MyNode*>::iterator iterator;
  for (iterator it = std::begin(my_list), end = std::end(my_list); it != end; ++it)
    delete *it;  // manually releases our allocated memory from the heap
  // the "head" is still deleted automatically because it is stack allocated
  // (the list object)
}

如果不再有訪問節點的方法(它們仍在內存中),那么可以,那就是泄漏。 語言本身不會以任何方式處理內存泄漏,但是現代操作系統會在進程結束后進行清理,因此(最終)內存泄漏確實會得到解決,但只能在進程執行結束時進行。 (但是,切勿在您之后依賴操作系統進行清理-作為程序員,這是一件可怕的事情。)

是的,這是內存泄漏。 不,C和C ++(沒有C / C ++這樣的語言)都沒有任何機制來處理此問題。 它們不是JAVA或更高版本的語言。 作為編碼員,完全取決於您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM