2013-03-22 125 views
0

我寫了一個使用全局堆的代碼。我需要多次重做相同的操作。每次我需要清除堆並重新分配數據。但vector :: clear()函數不釋放內存。所以一段時間後內存被填滿並且程序終止。錯誤:std :: bad_alloc在內存位置0x0038fd50

#include "stdafx.h" 
#include <cstdio> 
#include <vector> 
using namespace std; 

#define N 30000 
typedef unsigned int uint; 
class Node; 
class Edge; 
vector<Node*> nodes; 
vector<Edge*> edges; 

class Node 
{ 
public: 
    Node(uint id): id(id) 
    { 
     nodes.push_back(this); 
    } 
public: 
    uint id; 
}; 

class Edge 
{ 
public: 
    Edge(int nod1, int nod2) 
     : nodH(nod1), nodT(nod2) 
    { 
     edges.push_back(this); 
    } 
    bool Connects(Node* nod1, Node* nod2) 
    { 
     return (
      (nod1->id == this->nodH && nod2->id == this->nodT) || 
      (nod1->id == this->nodT && nod2->id == this->nodH)); 
    } 
public: 
    int nodH; 
    int nodT; 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    Node *nd; 
    for(long int i=0;i<N;i++) 
    { 
     for (int j=0;j<N;j++) 
     { 
      nd = new Node(j); 
     } 
     for (uint j=0;j<N;j++) 
     { 
      Edge* e = new Edge(j,N-j); 
     } 
     printf("%d %d ",nodes.size(),edges.size()); 

     // Do something here like calling function etc. 
     nodes.erase(nodes.begin()+N/2); 

     nodes.clear(); 
     edges.clear(); 
     //nodes.~vector(); 
     //edges.~vector(); 
     printf("%d %d\n",nodes.size(),edges.size()); 
    } 
    getchar(); 
    return 0; 
} 

我該怎麼辦?我嘗試了vector ::〜vector()函數。但那並不奏效。 任何人都可以幫我解釋如何釋放「清除」的內存空間嗎?

回答

0

衆所周知的訣竅是臨時創建一個

template< class T > 
void clearVector(std::vector<T> & v) 
{ 
    std::vector<T> dummy; 
    std::swap(v, dummy); 
} 

掉你的載體BTW,使用矢量與原始指針是不是一個好主意。我會建議std::shared_ptr或類似的。如果(出於某些令人驚訝的原因)你不能使用智能指針,那麼你應該調用這樣的功能

struct die { 
    template <class T> void operator()(const T * p) const { delete p; } 
}; 
template< class InputIterator > 
inline void kill_em_all(const InputIterator & begin, const InputIterator & end) 
{ 
    std::for_each(begin, end, die()); 
} 

... 
kill_em_all(vector_to_clear.begin(), vector_to_clear.end()); 
+0

我試過以下內容: \t \t \t ** vector temp_nod; \t \t \t vector temp_edg; \t \t \t swap(nodes,temp_nod); \t \t \t swap(edges,temp_edg); \t \t \t temp_nod。〜vector(); \t \t \t temp_edg。〜vector(); ** 但它仍然無法正常工作。 – 2013-03-22 10:10:33

+0

無法理解哪些不起作用...是否要刪除矢量(由Edge * e = new Edge(j,N-j);')創建的所有元素? – borisbn 2013-03-22 10:13:15

+0

程序使用的內存仍在增加。 向量中的元素正在被刪除。但內存空間並未被釋放。 :( – 2013-03-22 10:20:11

0

原因vector.clear()不會刪除的對象是你保持原始指針在兩個載體:

vector<Node*> nodes; 
vector<Edge*> edges; 

你要麼必須自己解除分配的元素,或者更好,使用智能指針(例如,std::unique_ptr )。

+0

有什麼出路嗎?你能幫我嗎? – 2013-03-22 09:58:08

0

您正在爲應用程序分配一個巨大的內存堆。嘗試減少你的N爲100開始。 bad_alloc通常表示運行時無法保留內存。

+0

我知道。但是我需要大量的數據。 – 2013-03-22 10:03:40

相關問題