3

関数を呼び出すと、一番下の 2 行のコードtail = head; tail->next= NULL;によってプログラムがクラッシュしextractMin()ます。それらをコメントアウトすると、すべてが想定どおりに行われます。これは、解放されたメモリ内のアドレスを指しているために発生していますか?

コンパイラが私に与える唯一の手がかりはこれです: 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++;
    }
4

1 に答える 1

3

あなたのelse条項は壊れています。null の場合prev、最初の要素の前に挿入しようとしています。

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

設定tail->next = NULLはコアエラーです。

于 2013-01-14T22:17:03.970 に答える