I am trying to implement the adaptive huffman code, but while trying to build the tree i get a segmentation fault when executing the code at line "currentNYT->lchild = newNYT;" in addnode() function.
Could anyone please help me out? It might be something simple i'm not aware of. didn't use C for a while now.
//variable and type declarations
struct treeElement {
unsigned long weight;
unsigned short id;
char chr;
struct treeElement *lchild, *rchild, *parent;
};
typedef struct treeElement node;
node *root, *currentNYT;
//functions
void initTree() {
root = NULL;
currentNYT = malloc(sizeof(node));
currentNYT = root;
} //initTree
void addNode(char newNodeChr) {
node *newNYT, *newExternal;
newNYT = 开发者_JS百科malloc(sizeof(node));
newNYT->id=maxNodes-idCount; idCount++;
newNYT->chr='\0';
newNYT->weight=0;
newNYT->parent=currentNYT;
newNYT->lchild=newNYT->rchild=NULL;
newExternal = malloc(sizeof(node));
newExternal->id=maxNodes-idCount;
newExternal->chr=newNodeChr;
newExternal->weight=1;
newExternal->parent=currentNYT;
newExternal->lchild=newExternal->rchild=NULL;
currentNYT->lchild = newNYT;
currentNYT->rchild = newExternal;
currentNYT=newNYT;
} //addNode
The following seems to be a first error...
currentNYT = malloc(sizeof(node));
currentNYT = root;
Probably want
root = malloc(sizeof(node));
currentNYT = root;
instead
Look at this:
root = NULL;
currentNYT = malloc(sizeof(node));
currentNYT = root;
You set root
to NULL
, then you set currentNYT
to root
. Therefore currentNYT
is always NULL
.
root = NULL;
currentNYT = malloc(sizeof(node));
currentNYT = root;
Um, you're setting currentNYT to NULL. Did you mean to do:
root = currentNYT;
instead?
You may want to initialize the elements of that node too. Oh, and perhaps check that malloc succeeded?
Might be clearer to do
root = malloc(sizeof(node));
if (!root) {
/* panic! */
}
root->.... = whatever; /* for each of the elements of the struct */
currentNYT = root;
Yes removing currentNYT = root will get me rid of the segfault but unfortunately it won't do what I want.
I want to initialize my tree. The root will be empty with NULL children. currentNYT will initially point to root.
addNode() will always add two new child nodes to the currentNYT node. The left child will be the newNYT and the right node will be the node that has the value sent as the argument of the function. The next call of addNode() will do the same but the two new nodes' parent will be the newNYT, therefore currentNYT must point to newNYT after the first call of addNode().
currentNYT will always point to the node that will serve as parent on the next call of addNode().
I really hope someone can help.
精彩评论