繁体   English   中英

指针分配错误

[英]Segmentation fault on pointer to pointer assignment

我正在实现霍夫曼压缩,并且正在从包含节点的链接列表中构建霍夫树。 多次迭代后,我在指向分配指针的指针上遇到分段错误。 根据我的经验和研究,我相信分段错误是由于错误而不是程序中断引起的。 任何帮助或建议,将不胜感激。

PS-我是堆栈溢出的新手,从没问过任何问题,所以请告诉我您是否需要更多信息以帮助我解决此问题或其他问题。

struct LinkList{
    int weight;
    struct TreeNode * bottom;
    struct LinkList * next;
}; typedef struct LinkList LinkList;

//This function takes in a link list where each node points to the next
 //element in the link list and a huff tree node. It also contains weight 
//which is equal to the weight of the hufftree that it points to.

TreeNode * huffTree(LinkList * head)
{
    LinkList * temphead = head;
    LinkList * ptr;
    LinkList * ptr1;
    int count = 127,i;
    while(count>2)
    {
        temphead = head->next->next;
        head->next->next = NULL;
        head = mergeTree(head);
        ptr = temphead;
        ptr1 = temphead;// This is where I get the segmentation fault
//when the value of count is 14
        while(head->weight>temphead->weight)
        {
            ptr1 = temphead;
            temphead = temphead->next;
        }

        if(ptr1!=temphead)
        {
            head->next = temphead;
            ptr1->next = head;
            head = ptr;
        }

        else
        {
            head->next = temphead;
        }

        count--;
    }

    head = mergeTree(head);

    TreeNode * root;
    root = head->bottom;
    head->bottom = NULL;
    free(head);
    return root;
}

LinkList * mergeTree(LinkList * head)
{
    TreeNode * tree1 = head->bottom;
    TreeNode * tree2 = head->next->bottom;
    head->bottom = NULL;
    head->next->bottom = NULL;

    free(head->next);
    free(head);

    TreeNode * newnode = (TreeNode *) malloc(sizeof(TreeNode));

    newnode->weight = tree1->weight + tree2->weight;
    newnode->c = '~';
    newnode->left = tree1;
    newnode->right = tree2;

    LinkList * ptr = (LinkList *) malloc(sizeof(TreeNode));
    ptr->weight = newnode->weight;
    ptr->bottom = newnode;
    ptr->next = NULL;

    return ptr;
}

我的猜测是在语句“ while(head-> weight> temphead-> weight){}”上。 当您遍历列表时,尚未检查磁头是否已变为NULL。

在您的“ huffTree()”函数中,外部while循环(while(count> 2))运行127次迭代,因为count是用129初始化的。

因此,当调用方调用huffTree()时,输入列表(LinkList * head)必须具有129个可用节点。

无论如何,如果列表中的节点少于129个,则应添加以下NULL条件处理。

temphead = head->next->next;
if (NULL == temphead)
{
    /* NULL condition handling */
}

当temphead == NULL时,temphead-> weight解引用将导致以下代码行中的分段错误

while(head->weight>temphead->weight)

如果确保malloc()在mergeTree()函数中不会失败,则head-> weight很好。

暂无
暂无

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

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