语句内分配"if"内存,退出时解除分配
Memory allocated within "if" statement, deallocated upon exit
我正在输入一个"if"语句,删除链表中动态分配的节点,然后重新分配它。问题是,一旦退出该语句,内存就会消失。以下是相关代码:
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中,直到我离开"if"语句。一旦我离开,它就会变成一个空指针。当我删除return
,转而转到else
部分时,也会发生这种情况。我一离开if
区域,记忆就消失了。
您没有重新分配if
语句中的任何内容。您正在声明一个完全独立的局部变量,其名称与headByName
相同。该局部变量在块的末尾被销毁,就像任何其他局部变量一样。
停止尝试声明局部变量。如果你想重新分配你的节点,你应该做一些类似的事情
headByName = new Node(winery);
你说这是一个链接列表,所以你可能也必须以某种方式将它正确地链接到列表中,但这是你必须自己做的事情。
您的变量是在if作用域内创建的,因此在作用域末尾被删除。以与相同的方式
void foo()
{
int b;
while ()
{
int a;
}
}
b在foo()范围内是可访问的,a在while的foo范围内是可以访问的,并且它们都不能在foo()之外访问。
相关文章:
- 指针会被解除分配吗?
- 基于浅树的数据结构的内存分配器,用于频繁分配和解除分配
- 解除分配矩形 2D 数组会根据尺寸产生错误
- 为什么在正确解除分配内存时出现内存泄漏?
- 堆栈变量超出范围时是否解除分配?
- 如何在不使用 "new" 关键字的情况下解除分配创建的对象的内存?
- 在 QStandardItemModel 中解除分配项目
- 解除分配此特定 2D 阵列的内存
- C++删除数组只会解除分配第一项
- 在 c++ 中使用向量解除分配
- 与解除分配堆数组相关的语法混淆
- 解除分配与 C++ 中的结构关联的所有内存
- 是否随作用域分配和解除分配堆栈帧
- 如果我使用 std::function 来捕获 lambda,我应该担心它被解除分配吗?
- 如果清除了 std::map 是否确保内存被解除分配
- 在另一个结构中的结构内解除分配指针
- 由 strcpy 设置的解除分配字符 * 时内存泄漏?
- 自定义内存分配和多个继承类的解除分配
- libpq错误消息解除分配
- 语句内分配"if"内存,退出时解除分配