2015-10-06 103 views
1

我正在实现huffman压缩,我正在从包含节点的链接列表构建hufftree。在多次迭代之后,我在指向指定的指针上收到了段错误。根据我的经验和研究,我认为分段错误是由于程序中断以外的错误。任何帮助或建议将不胜感激。我是新来的堆栈溢出,从来没有问过一个问题,所以请让我知道如果你需要更多的信息来帮助我解决这个问题或其他任何问题。指针指向分割错误

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; 
} 
+0

这是C还是C++?它看起来像C. –

+0

@PCLuddite - 是的它是c代码 –

+0

@jakshay_desai然后你应该删除C++标记。 –

回答

0

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

+0

我在出现seg故障之前打印出列表并且它不是空的因此头不是空的。为了避免刚刚描述的情况,我已经开始使用(计数> 2)。当计数= 14时,程序给了我一个seg错误。所以一切正常,除了我在其他程序中出现了一些错误之外,在程序中它不会影响代码,直到计数下降到14为止。 –

0

在你的 “huffTree()” 功能,外部while循环(而(计数> 2)),因为计数与129

所以,当huffTree()被调用者称为初始化运行127次迭代,输入列表(LinkList * head)必须有129个节点可用。

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

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

当temphead == NULL,则temphead->重量derefrencing将导致分段故障在下面的代码行

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

头戴式>重量,如果malloc()函数是有保证不失败是细在mergeTree()函数中。

+0

没错!然而,你所建议的完全有道理,但是这个函数失败的测试用例在129个节点列表中发送(每个ascii字符占用一个节点)。我在分配ptr1 = temphead的seg故障之前打印出列表和temphead;两者都不是NULL。现在使用逻辑我知道如果temphead!= NULL,ptr1 = temphead不是问题。问题存在于代码中的其他地方(可能在mergetree中),但我无法弄清楚究竟是什么或可能的技术来调试 –