我正在为Quadtree创建一个复制构造函数。这是我到目前为止所做的:
//Copy Constructor
Quadtree :: Quadtree(const Quadtree & other)
{
root = copy(other.root);
resolution = other.resolution;
}
//Copy Constructor helper function
Quadtree::QuadtreeNode *Quadtree :: copy (const QuadtreeNode* newRoot)
{
if (newRoot != NULL)
{
QuadtreeNode *node = new QuadtreeNode(newRoot->element);
node->nwChild = copy(newRoot->nwChild);
node->neChild = copy(newRoot->neChild);
node->swChild = copy(newRoot->swChild);
node->seChild = copy(newRoot->seChild);
return node;
}
else
return NULL;
}
我不确定我哪里出错,但我收到了内存泄漏,Valgrind指出我有未初始化的值。请帮忙吗?
附上,是我的buildTree函数 - 我实际创建了树。我可能在这里做错了什么?
void Quadtree :: buildTree (PNG const & source, int theResolution)
{
buildTreeHelp (root, 0, 0, theResolution, source);
}
void Quadtree :: buildTreeHelp (QuadtreeNode * & newRoot, int xCoord, int yCoord, int d, PNG const & image)
{
if (d == 1)
{
RGBAPixel pixel = *image(xCoord, yCoord);
newRoot = new QuadtreeNode(pixel);
return;
}
newRoot = new QuadtreeNode ();
newRoot = NULL;
buildTreeHelp(newRoot->nwChild, xCoord, yCoord, d/2, image);
buildTreeHelp(newRoot->neChild, xCoord + d/2, yCoord, d/2, image);
buildTreeHelp(newRoot->swChild, d/2, yCoord + d/2, d/2, image);
buildTreeHelp(newRoot->seChild, d/2 + xCoord, d/2 + yCoord, d/2, image);
}
答案 0 :(得分:1)
我认为内存泄漏就在这里:
newRoot = new QuadtreeNode ();
newRoot = NULL;
您正在分配内存,然后将指针设置为NULL
而不取消分配内存。另外,在下一行中,您尝试取消引用刚刚设置为NULL的指针:
buildTreeHelp(newRoot->nwChild, xCoord, yCoord, d/2, image);
使用std::unique_ptr
之类的智能指针管理内存而不是使用new
和delete
的原始调用,您可能会受益。