【问题标题】:Null pointer comparison in CC中的空指针比较
【发布时间】:2013-10-18 01:41:19
【问题描述】:

我不明白为什么我不输入这个 if statement(temp->next)->next 是 0。我也尝试将 (temp->next)->next 转换为 (void*) 但它没有用!

    void Mem_Coalesce(){


    list_t* temp;
    temp = freep;
    if( free_node_count == 2){

        if( ((char*)temp + (temp->size) )  == (char*)(temp->next)){
                printf("Entered if loop\n");
                        temp->size += (temp->next)->size;
                temp->next = NULL;
                free_node_count--;
        }



    }
    else {
         printf("\n coalescing the case that free list has 3+ nodes\n");
        while(temp->next != NULL  ){

            if( ((char*)temp + (temp->size)) == (char*)(temp->next)){

                    if( (temp->next)->next == NULL){

                        temp->size += (temp->next)->size;
                        temp->next = NULL; //seg fault happens here 
                                                break;


                    }else{

                    temp->size += (temp->next)->size;
                                        temp->next = (temp->next)->next;
                    ((temp->next)->next)->prev = temp;
                    }
                    free_node_count--;

            }
            temp=temp->next;

        }

    }



}

这是我收到的有段错误的输出:

Addr of temp->next is  7f4a836ae2e8

Addr of temp->next->next is  0

./cmd.sh: line 5: 31230 Segmentation fault      (core dumped) myprogram

我是否错误地将指针值与 NULL 进行了比较?

【问题讨论】:

  • 第 5 行是什么?是if语句吗?
  • @KristerAndersson:该消息与 C 代码无关,它只是说明崩溃发生在从 cmd.sh shell 脚本的第 5 行开始的程序中。
  • -g 添加到编译标志,然后使用gdb。在gdb 中使用run,然后使用backtrace。它应该告诉您崩溃发生在哪一行。这应该可以帮助我们找出程序出了什么问题。
  • 我希望您的“if”块(第 5 行)之后的第一行尝试使用 (temp->next)->next 执行某些操作,可能会取消引用它。它为空,因此这将导致段错误。
  • 请将整个代码粘贴到问题中。你显示的没有错。

标签: c pointers null linked-list segmentation-fault


【解决方案1】:

我认为问题源于没有 break 。在temp->next=NULL 之后没有break。现在已经修复了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 2018-08-05
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多