分配链表后的分段错误

时间:2012-02-09 14:28:14

标签: c linked-list dynamic-memory-allocation

我需要在程序中创建一个链表。在我的程序中,列表使用malloc()分配在堆上,而不是我尝试访问它但是我得到了一个segmetation错误;

编辑:我在这一行获得了SIGSEGV“而(!(node-> nodeType == TYPE_END_LIST)){”

    struct dagNode *createList(int k);
    struct dagNode *newNodeXInterval(int type, int val);


    struct dagNode *createList(int k){
    struct dagNode *head, *node;
    printf("\nList %d = ", k);
    head = newNodeXInterval(TYPE_EDGE_OR_GAP, getVal(k,1));
    node = head;
    int i;
    for (i=1; i<LENGTH_OF(k); i++){
            node->next = newNodeXInterval(TYPE_XTEST, getRightPointOf(k,i));
            node = node->next;
            node->next = newNodeXInterval(TYPE_EDGE_OR_GAP, getVal(k,i+1));
            node = node->next;
            }     
    node = newNodeXInterval(TYPE_END_LIST, 0);
    node = head;     // i think that here there is the error
    printf("%d", node->val); i=0;
                    while(!(node->nodeType == TYPE_END_LIST)){
                        printf("%d ", i);
                        node = node->next;}
    return head;}


    struct dagNode *newNodeXInterval(int type, int val){
        struct dagNode *node = (struct dagNode *) malloc(sizeof(struct dagNode));
        if (type == TYPE_EDGE_OR_GAP){
        *node = (struct dagNode) {(val<0)? TYPE_GAP:TYPE_EDGE, val, NULL, NULL, NULL};
        }
        else{
        *node = (struct dagNode) {type, val, NULL, NULL, NULL};
        }
        return node;    }

调用者函数将成为列表的头部。

1 个答案:

答案 0 :(得分:1)

据我所知,问题在于行

node = newNodeXInterval(TYPE_END_LIST, 0);

在分配之前,node指向链接列表中的最后一个节点,而前一个节点的next指针等于node。在分配后,node指向新创建的类型为TYPE_END_LIST的节点,但前一个节点的next指针保持不变(即它仍保留原始值node )。换句话说,新创建的节点不是列表的一部分,因此以下node->nodeType == TYPE_END_LIST循环中的条件while()永远不会计算为true,并且最终会取消引用空指针当你超过列表的末尾。将行更改为

node->next = newNodeXInterval(TYPE_END_LIST,0);     

应该解决问题。

相关问题