内存泄漏在我的程序中;析构函数是不被调用的?

时间:2017-02-18 23:36:44

标签: c++ memory-leaks valgrind destructor

我觉得我在这里砸砖墙。

我不确定析构函数是否实际被调用。我正在使用priority_queue来保存一堆节点。每个节点都有一个成员m_grid,它是结构的2D数组。这个网格代表我在程序中明确使用的唯一指针。

出于某种原因,我遇到了很多泄漏。你能救我一下吗?

这是析构函数:

grid::~grid()
{
  for (int i = 0; i < m_width; i++)
  {
    delete[] m_grid[i];
    m_grid[i] = NULL;
  }

  delete[] m_grid;
  m_grid = NULL;
}

赋值运算符:

grid& grid::operator=(const grid& g)
{
  m_x_rad = g.m_x_rad;
  m_y_rad = g.m_y_rad;
  m_width = g.m_width;
  m_height = g.m_height;
  m_orientation = g.m_orientation;

  if (m_width != 0)
    m_grid = new cell* [m_width];

  // from left to right
  for (int i = 0; i < m_width; i++)
  {
    m_grid[i] = new cell [m_height];

    // from top to bottom
    for (int j = 0; j < m_height; j++)
    {
      m_grid[i][j].m_occupied = g.m_grid[i][j].m_occupied;
      m_grid[i][j].m_rad = g.m_grid[i][j].m_rad;
    }
  }

  return *this;
}

赋值运算符与预期类似。 最后,这里有一些valgrind输出(有很多,但它都涉及grid :: setSize()或grid :: operator =。

==13329== 200 (40 direct, 160 indirect) bytes in 1 blocks are definitely lost in loss record 25 of 166
==13329==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13329==    by 0x4020C1: grid::operator=(grid const&) (grid.cpp:192)
==13329==    by 0x40A02E: node::operator=(node const&) (node.cpp:129)
==13329==    by 0x4075A6: __push_heap<__gnu_cxx::__normal_iterator<node*, std::vector<node> >, long int, node, __gnu_cxx::__ops::_Iter_comp_val<std::greater<node> > > (stl_heap.h:135)
==13329==    by 0x4075A6: push_heap<__gnu_cxx::__normal_iterator<node*, std::vector<node> >, std::greater<node> > (stl_heap.h:199)
==13329==    by 0x4075A6: push (stl_queue.h:502)
==13329==    by 0x4075A6: aStarGraphSearch(basic_map const&, node&, std::unordered_map<int, basic_node, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<int const, basic_node> > >&, std::priority_queue<node, std::vector<node, std::allocator<node> >, std::greater<node> >&) (main_functions.cpp:216)
==13329==    by 0x4088ED: search(int) (main_functions.cpp:706)
==13329==    by 0x401AAA: main (main.cpp:13)

我真的在这里挣扎。当我使用堆栈而不是优先级队列时,我没有遇到这些问题。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

您不能在分配运算符中删除m_grid(及其包含的数组)。

答案 1 :(得分:0)

对赋值运算符的调用不会首先自动调用析构函数。如果您要用新内存替换它,您必须自己清理该对象已拥有的所有内存。

作业不会成为新对象;它只是修改了你已经拥有的对象。