指向已释放内存空间的指针
C++: Pointers pointing to freed memory space
当我调用extractMin()
函数时,底部tail = head;
tail->next= NULL;
的两行代码导致程序崩溃。如果我把它们注释掉,一切都按预期进行。这是因为它们指向内存中已释放的地址吗?
编译器给我的唯一线索是:EXC_BAD_ACCESS (code=2, address=0x0)
。我立刻注意到地址是0所以这里有问题,但究竟是什么?
string LinkedListPQueue::extractMin() {
if (isEmpty())
error("Tried to dequeue from epmpty queue!");
cell *toBeDeleted = head; //pointer to this head
string value = head->value; //get value of this head
head = head->next; //move so this head is not the same as the one to be deleted
delete toBeDeleted; //delete previous head.
return value;
}
/* Implementation notes: enqueue
* -----------------------------
* We have to search to find the proper position, which can be a bit tricky with
* a singly-linked list. We walk two parallel pointers, one a step behind the other,
* until we find the correct position to insert the new cell, which we then splice
* into place. Note the special case of inserting at the head. Alternatively, this
* operation could work recursively.
*/
void LinkedListPQueue::enqueue(const string& elem) {
cell *cur, *prev, *newOne = new cell;
newOne->value = elem;
for (prev = NULL, cur = head; cur != NULL; prev=cur, cur = cur->next) {
if (elem > cur->value) break;
}
newOne->next = cur;
if (prev) {
prev->next = newOne;
logSize++;
} else {
head = newOne;
tail = head;
tail->next= NULL;
logSize++;
}
您的else
条款已失效。如果prev
是空的,那么你尝试在第一个元素之前插入。
else {
cell *oldHead = head;
head = newOne;
head->next = oldHead;
logSize++;
}
设置tail->next = NULL
是核心错误
相关文章:
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- 空向量占用的空间是否与指向当前设置为 nullptr 的类型的指针一样多
- 将空间分配给整数指针时出错
- 使用全局命名空间限定符和指向数据成员的指针
- 指向命名空间内的成员函数的指针
- 如何表示指向地址空间开头的指针
- 删除内存空间后,指针的值保持不变还是更改?对象内容是否将被更改
- 如何在分配更多内存空间之前检查指针是否为 NULL
- C++在boost python中使用带有命名空间的自定义智能指针
- 数组的指针,该数组的每个元素的内存空间信息存储在哪里
- 将指针添加到不同命名空间中的类时出错
- Do C和C++标准意味着地址空间中必须只存在一个特殊值来表示空指针的值
- 关于取消引用和地址空间的基本C++指针问题
- 初始化指针数据结构的空间复杂性
- c/c++中的指针及其内存空间
- 模板类内的成员到函数指针给出错误:后跟 '::' 时必须是类或命名空间
- 由 shmat 返回的指针位于地址空间的末尾,这给出了 SEG 错误
- 以何种形式,可以通过管道将空指针发送到不同进程地址空间中的另一个进程
- 修剪空间C++指针