错误:std::bad_alloc在内存位置0x0038fd50
Error: std::bad_alloc at memory location 0x0038fd50
我写了一个使用全局堆的代码。我需要多次重复同样的操作。每次我都需要清理堆并重新分配数据。但是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
通常表示运行时不能预留内存。
相关文章:
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 如何在不等待检索的情况下获取C++中的内存位置?
- 向量的内存位置不连续
- 如何根据C++在同一内存位置重新初始化 C# 中的对象(还是自动完成)?
- 常量引用的内存位置
- C++强制变量到一个固定的内存位置
- 为什么未初始化的内存位置的值给出 -842150451 的值?
- 为什么存储在内存位置的值会发生变化?
- 在特定内存位置构造 c++ 对象
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 内存位置出现Microsoft C++异常:std::out_of_range
- 函数,返回变量c++占用的内存位置的大小
- 无法在 Opencv 中显示图像导致内存位置
- 从十六进制到双的转换始终导致内存位置的 std::out_of_range
- 错误 在测试.exe 0x76C9FD62时出现未经处理的异常:Microsoft C++异常:内存位置0x006FF8
- 错误:内存位置的 std::length_error
- C++不同内存位置中的默认数组值
- 为什么动态分配的两个变量的内存位置不是连续的?
- Boost.进程间内存位置
- 查找编译时构造类的内存位置