Q:

Seg Fault in BST inorder traversal

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define n 5

struct node
{
    int num;
    char *symbol;
    char *code;
    struct node *left;
    struct node *right;
}*root_ptr, *current, *previous;

void form_bst_of_dividing_positions();
void inorderTraversal(struct node *);

int dividing_positions[n], counter = 0;

int main(int argc, char *argv[])
{
    //code to populate dividing_positions

    //tree structure formation
    counter = 0;
    root_ptr = malloc(sizeof(struct node));
    root_ptr->num = dividing_positions[0];
    root_ptr->code = root_ptr->symbol = NULL;
    root_ptr->left = root_ptr->right = NULL;
    form_bst_of_dividing_positions();

    inorderTraversal(root_ptr);
    return 0;
}
void form_bst_of_dividing_positions()
{
    for(i=1;i<n;i++)
    {
        if(dividing_positions[i]==-1)
            break;
        else
        {
            struct node nodeToAdd;
            nodeToAdd.num = dividing_positions[i];
            nodeToAdd.code = nodeToAdd.symbol = NULL;
            nodeToAdd.left = nodeToAdd.right = NULL;

            current = previous = root_ptr;
            while(current!=NULL)
            {
                previous = current;
                current = (dividing_positions[i]<(current->num))? current->left : current->right;
            }
            if(nodeToAdd.num<(previous->num))
                previous->left = &nodeToAdd;
            else
                previous->right = &nodeToAdd;
        }
    }
}
void inorderTraversal(struct node *no)
{
    if(no!=NULL)
    {
        inorderTraversal(no->left);
        printf("%d ", no->num);
        inorderTraversal(no->right);
    }
}

Above code gives me Segmentation fault .. in Codeblocks the output window prints 4 infinitely. 2, 3, 1, 4 = to be inserted into BST. Ive converted my Java code to C, are there any specifics to be handled in my above code?
Thanks..

A:

Your nodeToAdd is a local variable, its address becomes invalid once you leave that code block. You should use malloc to create new nodes (and free them with free eventually).

