在“if”语句中分配的内存,在退出时取消分配

时间:2014-10-13 00:06:45

标签: c++

我正在进入"如果"声明并删除链接列表中的动态分配节点,然后重新分配它。问题是,一旦我退出语句,内存就会消失。以下是相关代码:

if (!headByName)                    //if the node is empty,
    {
        delete headByName;          //deallocate the memory that it has been given, and
        Node headByName(winery);    //reallocate it with the information contained within
                                    //"winery" copied into it 
        return;                     //looking at memory, everything works at this point
    }                               // <- this point right here is where the information goes "poof" and disappears                             

这是Node的构造函数:

List::Node::Node(const Winery& winery) :
item(winery.getName(), winery.getLocation(), winery.getAcres(), winery.getRating()),
nextByName(nullptr),
nextByRating(nullptr)
{

}

当我使用调试器时,所有内容都复制到headByName中,直到我离开&#34; if&#34;声明。一旦我离开,它就变成了一个空指针。当我移除return并转而转到else部分时,也会发生这种情况。一旦我离开if区域,记忆就会消失。

2 个答案:

答案 0 :(得分:2)

您的变量是在if范围内创建的,因此会在范围的末尾删除。 与

相同的方式
void foo()
{
   int b;
   while ()
   {
    int a;
   }
}

b在foo()范围内是可访问的,a可以在while的foo范围内访问,并且在foo()之外都不可访问它们。

答案 1 :(得分:2)

您没有在if声明中重新分配任何内容。您正在声明一个名为headByName的完全独立的局部变量。就像任何其他局部变量一样,该局部变量在块的末尾被破坏。

停止尝试声明局部变量。如果您想重新分配您的节点,您应该执行类似

的操作
headByName = new Node(winery); 

你说它是一个链表,所以你也可能不得不以某种方式将它正确地链接到列表中,但这是你必须自己做的事情。