Tom Lilletveit
Tom Lilletveit

Reputation: 2002

C++: Pointers pointing to freed memory space

The two lines of code at the bottom tail = head; tail->next= NULL; causes the program to crash, when I call the extractMin() function. If i comment them out, everything is happening as supposed. Is this happening cause they are pointing to addresses in memory that has been freed?

The only clue the compiler gives me is this:EXC_BAD_ACCESS (code=2, address=0x0). I notice immediately the address being 0x0 so there is a problem there, but what exactly?

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++;
    }

Upvotes: 3

Views: 336

Answers (1)

Mel Nicholson
Mel Nicholson

Reputation: 3225

Your else clause is broken. If prev was null, then you are trying to insert before the first element.

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

Setting tail->next = NULL is the core error.

Upvotes: 3

Related Questions