C++图形函数内存泄漏(valgrind在线上没有具体说明)

Memory Leak In C++ Graph Function (valgrind not specific on line)

本文关键字:说明 在线 函数 图形 内存 泄漏 valgrind C++      更新时间:2023-10-16

我正在用C++中的边列表实现一个Graph。代码按预期执行,但根据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分配的内存没有释放(释放)。

是否释放了顶点而没有释放边?