错误:std::bad_alloc在内存位置0x0038fd50

Error: std::bad_alloc at memory location 0x0038fd50

本文关键字:内存 位置 0x0038fd50 std bad 错误 alloc      更新时间:2023-10-16

我写了一个使用全局堆的代码。我需要多次重复同样的操作。每次我都需要清理堆并重新分配数据。但是vector::clear()函数不会释放内存。一段时间后,内存被填满,程序终止。

#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 %dn",nodes.size(),edges.size());
    }
    getchar();
    return 0;
}

我能做什么?我尝试了vector::~vector()函数。但这并没有奏效。谁能帮助我关于如何释放"清除"的内存空间?

众所周知的技巧是将您的矢量与临时创建的矢量交换

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

顺便说一句,使用vector和原始指针不是一个好主意。我建议使用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() );

vector.clear()不删除对象的原因是您在两个向量中保留了原始指针:

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

您必须自己释放元素,或者更好的是使用智能指针(例如,std::unique_ptr)。

您正在为应用程序分配一个巨大的内存堆。尝试减少你的N到100开始。bad_alloc通常表示运行时不能预留内存。