c++ - C++ Graph Function 中的内存泄漏(valgrind 未具体在线)

标签 c++ graph memory-leaks

我正在使用 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/

相关文章:

c++ - 函数指针是否有声明?

c++ - 在用 C++ 编写字符串的过程中按 'Enter'

javascript - 哈密​​顿路径

python - 连接列表中的连续单词

python-3.x - 如何在 Python 中创建具有每个变量值之间差距的堆积条形图

c++ - boost posix_time 的字符串,然后再返回

c++ - 如何使函数不要求基于初始输入的额外输入

python - 使用 `as_ptr()` 时如何阻止内存泄漏?

c++ - QT:如何正确清理QSettings以防止内存泄漏?

php - NSURL请求:EXC_BAD_ACCESS