LYM
LYM

Reputation: 53

Singly Linked List EXC_BAD_ACCESS

I'm trying to write a remove function for a singly linked list and got this error message:

Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

What does this message mean and how shall I fix it?

void fifoqueue_remove(Fifoqueue_Ptr queue_ptr, void * this_call){
    Queue_Container_Ptr position = queue_ptr->front_ptr; //make position head
    while (position->next_ptr != NULL){
        if (position->next_ptr->content_ptr == this_call){
            Queue_Container_Ptr next = position->next_ptr;
            position->next_ptr = next->next_ptr;
            free((char*) position); //remove position
        }
        else{
            position = position->next_ptr;
        }
    }
}

Upvotes: 0

Views: 49

Answers (1)

paddy
paddy

Reputation: 63481

Your loop is doing bad things with position which, if not the actual issue, is definitely undesirable.

As currently written, if you find the value to remove, you are calling free(position); and then continuing the loop. The very next thing that will happen is you access position->next_ptr, dereferencing a memory address that you returned to the system only moments ago.

This is likely to result in a crash if you're lucky. Possibly you're compiling in non-optimized mode where the memory manager is writing a byte pattern over any freed memory, so that attempts to use it are far more likely to result in bad pointer access.

I see you have actually prepared for the "correct approach" here but forgotten to do it:

// You remembered to save position->next_ptr
Queue_Container_Ptr next = position->next_ptr;

// ...

free(position);

// But you forgot to do this:
position = next;

It should also be mentioned that you are not handling the very last element in the list. Or perhaps that's not necessary because your list has a dummy tail node or something. It's hard to be sure, given what you've shown. But you should make sure that you test removal of a value that is the last position. You might discover a bug there.

Upvotes: 2

Related Questions