我正在使用 C++ 中的边列表实现图形。代码按预期执行,但根据 valgrind 的说法,存在由 AddEdge 函数引起的内存泄漏。我无法弄清楚它是什么,因为 AddEdge 和 AddVertex 相似,但 AddVertex 不会泄漏。
void Graph::AddVertex(string v)
{
bool full = false;
try
{
VertexNode* location = new VertexNode;
delete location;
full = false;
}
catch(std::bad_alloc exception)
{
full = true;
}
if(full == true)
throw GraphFull();
else
{
VertexNode* temp = new VertexNode;
temp->vname = v;
if (vertices == NULL)
{
vertices = temp;
vertices->nextVertex = NULL;
edges = NULL;
}
else
{
temp->nextVertex = vertices;
vertices = temp;
}
}
}
void Graph::AddEdge(string s, string d, int w)
{
bool full = false;
try
{
EdgeNode* location = new EdgeNode;
delete location;
full = false;
}
catch(std::bad_alloc exception)
{
full = true;
}
if(full == true)
throw GraphFull();
else
{
EdgeNode* temp = new EdgeNode;
temp->weight = w;
VertexNode* search = vertices;
while(search->vname != s)
search = search->nextVertex;
temp->source = search;
search = vertices;
while(search->vname != d)
search = search->nextVertex;
temp->destination = search;
if (edges == NULL)
{
edges = temp;
edges->nextEdge = NULL;
}
else
{
temp->nextEdge = edges;
edges = temp;
}
}
}
这是 valgrind 的输出:
==17435== at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==17435== by 0x401952: Graph::AddEdge(std::string,std::string,int)(in /home/graph)
==17435== by 0x402255: main (in /home/graph)
最佳答案
AddEdge 和 AddVertex 都不会释放它们分配的任何内存,因此根据设计,问题根本不在这些例程中。明确地说,内存泄漏是在程序关闭之前未能释放内存。仅报告说,特定例程分配的内存在程序退出时仍保持分配状态。
问题很可能不是在AddEdge
分配的时候,而是在程序退出的时候,AddEdge
分配的内存没有释放(freed) .
你是否释放了顶点而不是边?
关于c++ - C++ Graph Function 中的内存泄漏(valgrind 未具体在线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20260427/