简体   繁体   English

单链表 EXC_BAD_ACCESS

[英]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;
        }
    }
}

Your loop is doing bad things with position which, if not the actual issue, is definitely undesirable.您的循环在position做坏事,如果不是实际问题,那绝对是不可取的。

As currently written, if you find the value to remove, you are calling free(position);如目前所写,如果您找到要删除的值,则调用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.接下来将发生的事情是您访问position->next_ptr ,取消引用您刚才返回给系统的内存地址。

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.你可能会在那里发现一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM