Illes Peter
Illes Peter

Reputation: 1674

Segmentation Fault - Displaying Tree

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

Upvotes: 0

Views: 152

Answers (3)

Joy Dutta
Joy Dutta

Reputation: 3426

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.

Upvotes: 1

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14327

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.

Upvotes: 0

Tim
Tim

Reputation: 60150

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.

Upvotes: 2

Related Questions