【问题标题】:C, Segmentation Fault in linked listC、链表中的Segmentation Fault
【发布时间】:2018-07-03 14:57:33
【问题描述】:

下面的函数有问题,当 (*ptr) 为 NULL 而不是结束 while 循环时,函数会崩溃。我试过使用if((*ptr)->next==NULL) break;,但它还是失败了。

boolean search_times(struct list ** ptr, float *V, int n, struct list_times ** new ){

    struct list * tmp_ptr=NULL;

    if( V!=NULL && n>=0 ) {
        while((*ptr)!=NULL) {

            int times=0;

            for (int i = 0; i < n; i++) {
                if (isequal((*ptr)->value, V[i]))
                    times++;
            }

            if((suf_insert_times(new, (*ptr)->value, times))==FALSE)
                return FALSE;

            tmp_ptr=*ptr;
            ptr=&(*ptr)->next;
            free(tmp_ptr);
        }
        return TRUE;
    }
    else
        return FALSE;
}

【问题讨论】:

  • 是时候学习如何调试你的程序了stackoverflow.com/questions/25385173/…
  • 你的struct list 看起来像什么?
  • 这个程序我已经调试过了,不然我根本不知道它在这个时候崩溃了。无论如何感谢您的解决方案。
  • 是的,我想销毁它;)

标签: c linked-list segmentation-fault


【解决方案1】:

ptr=&amp;(*ptr)-&gt;next; 保存指向对象成员next 的指针,该对象在下一行中被释放。尝试在下一次迭代中取消引用 ptr 将导致未定义的行为。

*ptr = (*ptr)-&gt;next; 应该是正确的。这会将列表推进到下一项,而前一项将在下一行中释放。

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多