c - Building a Huffman tree from a binary search tree -


i trying build huffman tree out of binary search tree. sadly code crashing (segmentation fault (core dumped)).

this how struct defined:

struct node {   unsigned char m_ch;   int m_freq;   struct node *m_ls,*m_rs;   struct node *m_hls,*m_hrs; }; 

delmin passed double pointer binary search tree, , deletes leftmost leaf unless reaches node m_ch==0 , return deleted node

i can't find mistake

struct node *delmin(struct node **root) {     struct node *current = *root;     struct node *b4current;      if (current == null)         return null;      while (current->m_ls != null)     {         if (current->m_ch == 0)             break;          b4current = current;         current = current->m_ls;     }      if (current->m_ch == 0)         b4current->m_ls = null;     else     {         if (b4current == null)             *root = current->m_rs;         else             b4current->m_ls = current->m_rs;     }      return current; }   struct node *huffman(struct node *root) {     struct node *left;     struct node *right;     struct node *temproot;     struct node *huffmantree;      while (root->m_ch != 0)     {         left = delmin(&root);         right = delmin(&root);         temproot = createnode((left->m_freq) + (right->m_freq), 0);         temproot->m_hls = left;         temproot->m_hrs = right;         inserttree(&root, temproot);     }      huffmantree = temproot;     return huffmantree; } 

edit: added code inserttree function called huffman

void inserttree(struct node **root,struct node *n) {   if (!*root)   {     *root=n;     return;   }   if(n->m_freq<(*root)->m_freq)   {     inserttree(&((*root)->m_ls),n);   }   else   {     inserttree(&((*root)->m_rs),n);   } } 

in delmin code section

if (current->m_ch == 0)     b4current->m_ls = null; else {     if (b4current == null)         *root = current->m_rs;     else         b4current->m_ls = current->m_rs; } 

there no guarantee b4current not null.

consider case root node has m_ch == 0 , m_ls == null. take if branch , dereference b4current.

you need initialize b4current null , check before dereference.

you need ensure root non-null before initializing current = *root in delmin or dereferencing in huffman

these should initialized null

struct node *left; struct node *right; struct node *temproot; struct node *huffmantree; 

and possible, again, never enter while loop, leaving temproot unset causing potential segfault in caller of huffman when return value.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -