views:

64

answers:

4

I get a segfault when calling viewTree(root);

    struct treeElement {
        unsigned long weight;
        unsigned short id;
        char chr;
        struct treeElement *lchild, *rchild, *parent;
    };

    typedef struct treeElement node;

    node *root;

    //INITIALIZE TREE
    void initTree() {
        root = malloc(sizeof(node));
        currentNYT = root;
    } //initTree

    //VIEW TREE
    void viewTree(node *tree) {
        printf("%5d%5d%5d%5d%5c%lu", tree->id, tree->parent->id, tree->lchild->id, tree->rchild->id, tree->chr, tree->weight);
        viewTree(tree->lchild);
        viewTree(tree->rchild);
    }

//ADD NODE
void addNode(char newNodeChr) {
    node *newNYT, *newExternal;
    newNYT = 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

int main()
{
    initTree();
    addNode('a');
    addNode('b');
    viewTree(root);

    getchar();

    return 0;
}
+2  A: 

Does the root node have a parent? Do the child leaf nodes have left and right children?

I think most of your problem lies in your printf statement - you don't check whether or not any of the objects you're accessing actually exist before you try to print their ids. Add some if statements in there and see if it helps.

Tim
+1  A: 

In your viewTree(node *tree) you are not checking if tree is null or not. Definite recipe for segfault when you try to access tree->id when tree is null.

null will be passed for a subtree in a recursive call eventually.

EDIT: In general you have check for null every time you need to access a member of an object. So, tree != null before reading tree->id and tree->lchild != null before reading tree->lchild->id must be ensured.

Joy Dutta
Also as answered by Tim, even if tree argument is NOT NULL, you still need to check parent, child, links for NULL before using them. +1 to both answers.
Van Gale
Yeah that too, before accessing deeper items.
Joy Dutta
A: 

Don't just allocate the root node, but initialize it, especially the pointers to siblings and to parent (set them to NULL). You are using the uninitialized pointers when adding nodes.

Cătălin Pitiș
A: 

Thank you guys!

I'd vote up all your answers (have to have 15 reps though).

I really have to revise my C skills. I didn't used to make errors like these a few years ago.

Illes Peter