gpt4 book ai didi

C++:指向释放内存空间的指针

转载 作者:太空狗 更新时间:2023-10-29 21:25:14 25 4
gpt4 key购买 nike

最下面的两行代码tail = head;
当我调用 extractMin() 函数时,tail->next= NULL;
导致程序崩溃。如果我将它们注释掉,一切都会按预期发生。发生这种情况是因为它们指向已释放的内存地址吗?



编译器给我的唯一线索是:EXC_BAD_ACCESS (code=2, address=0x0)。我立即注意到地址是 0x0,所以那里有问题,但究竟是什么?



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 为 null,那么您正试图在第一个元素之前插入。

else {
cell *oldHead = head;
head = newOne;
head->next = oldHead;
logSize++;
}

设置tail->next = NULL是核心错误。

关于C++:指向释放内存空间的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com