tags:

views:

90

answers:

2

hi, i am doing c program of binary tree while inserting the node to tree after 2 or 3 nodes the child node having garbage value and crashing i am doing in xcode any idea...

Bnode createTreeNode()
{
    Bnode node=(Bnode)malloc(sizeof(Bnode));
    return node;    
}

Bnode addTreeNode(Bnode inNode, char *inData)
{
    int compareValue;

    if (inNode == NULL)     
    {
        inNode = createTreeNode();

        inNode->leftNode=NULL;            
        inNode->rightNode=NULL;

        stpcpy(inNode->data,inData);        
    }
    else if((compareValue=strcmp(inData,inNode->data))==0)       
    {        
        inNode->count=inNode->count+1;

    }
    else if(compareValue>1)        
    {        
        inNode->rightNode=addTreeNode(inNode->rightNode,inData);    
    }
    else        
    {            
        inNode->leftNode = addTreeNode(inNode->leftNode,inData);        
    }

    return inNode;    
}

this is how i creating node and inserting it to tree.

+1  A: 

You declared a pointer for your node, but you didn't actually allocate any storage for it, so you have a dangling pointer. You need to call malloc() (or calloc()) for each new node, in order to allocate storage.

Paul R
Damn, you're good. Ok, how about this. I have this program that's supposed to do this thing, but it crashes. Can you help?
RarrRarrRarr
@RarrRarrRarr: sure - I see where you went wrong - change `if (x = 0)` to `if (x == 0)` - that should fix it. `;-)`
Paul R
+2  A: 
Bnode node=(Bnode)malloc(sizeof(Bnode)); //[1]
    return node;   

Argument of malloc is the size of the dynamic memory to be allocated.

You have provided size of the pointer to the struct as the argument instead of size of the struct itself.
As a result, less memory is allocated to Bnode and eventually you are bound to get garbage values and segmentation faults.


Change it to something like

Bnode node = malloc(sizeof(struct _bnode));
//where Bnode is pointer to struct _bnode

P.S.: [1] Explicit casts (Bnode) not required in C.

N 1.1