[英]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.