Thread: help with binary tree

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    4

    help with binary tree

    This is the instruction for my assignment:
    Write a program to process stock data. The stock data should be read from a text file containing the following data: stock code, stock name, amount invested (999.99), shares held, and current price.As each stock is read, insert it into a binary search tree (BST). The BST should be ordered on the stock code. (1½ marks)

    After building the BST, display a menu with the following options: (1 mark)

    (a) Display the BST in inorder traversal. Each display should contain an appropriate heading and column captions; (1 mark)

    (b) Search for a stock using the stock code and print the data for the stock; (1 mark)

    (c) Modify data for an existing stock; (2 marks)

    (d) Write the data back to the file you used to build the tree in the beginning of the program execution, and stop the program. (1½ marks)

    I have written the code but currently having problem with loading the list of stock stored in the file. The function of loading the code and inserting the stock into a binary tree are as follows:

    Code:
    void load(void)
    {
    	STOCK *info;
    	FILE *inp;
    
    	inp=fopen("stock.txt","r");
    	if(!inp)
    	{
    		printf("Cannot open file.\n");
    		exit(1);
    	}
    
    	//free any previously allocatd memory
    	while(root)
    	{
    		info=root->left;
    		free(info);
    		root=info;
    		info=root->right;
    		free(info);
    	}
    
    	root=NULL;
    
    	printf("\nLoading File.\n");
    	while(!feof(inp))
    	{
    		info=(STOCK*)malloc(sizeof(STOCK));
    		if(!info)
    		{
    			printf("Out of memory");
    			exit(1);
    		}
    
    		while((fscanf( inp," %[^\n]", &info->stockCode))!=EOF)
    		{
    			fscanf( inp," %[^\n]", &info->stockName);
    			fscanf( inp," %[^\n]", &info->amountInvested);
    			fscanf( inp," %[^\n]", &info->sharesHeld);
    			fscanf( inp," %[^\n]", &info->currentPrice);
    			root=stree(root, info);
    		}
    	}
    
    
    	if (fclose(inp)==EOF)
    		{
    			printf ("Error in closing file.\n");
    			exit (105);
    		}
    		else 
    		{
    			printf ("File is successfully loaded.\n");
    		}
    	system("pause");
    	system("cls");
    }
    Code:
    STOCK *stree(STOCK *r, STOCK *n)
    {
    	if(!r)
    	{
    		n->left=NULL;
    		n->right=NULL;
    
    		if(!root)
    			return n;
    		
    		if(strcmp(n->stockCode,root->stockCode) <0)
    			root->left=n;
    		else
    			if(strcmp(n->stockCode,root->stockCode) >0)
    				root->right=n;
    		return n;
    	}
    
    	if(strcmp(r->stockCode, n->stockCode) <0)
    		r=stree(r,r->right,n);
    	else
    		if(strcmp(n->stockCode,root->stockCode) >0)
    			r=stree(r,r->left,n);
    
    	return r;
    }
    I couldn't find the mistake where it only print out the last item. Any advise?
    I attached the full coding as well.
    Thanks.

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    There are a ton of things wrong with your code:

    1) Never flush stdin or any stream for that matter. That behavior is undefined. Beginners use fflush way to happily.

    2) Don't loop around feof(). Search the faq of this site for more info on that.

    3) This sequence of instructions makes no sense:

    free(info);
    root = info;

    4) You are misusing pointers quite a lot. Most times you just fail to allocate memory before using them or make them POINT TO SOMETHING that already exists.

    These are a few things to look for right now.

  3. #3
    Banned
    Join Date
    May 2007
    Location
    Berkeley, CA
    Posts
    329
    You aren't correctly free()ing the memory. What you need is a post order traversal in order to free() the nodes on your tree.
    Last edited by Overworked_PhD; 04-16-2010 at 08:05 AM.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by claudiu View Post
    1) Never flush stdin or any stream for that matter. That behavior is undefined. Beginners use fflush way to happily.
    Using fflush is fine on an output stream, and it is not undefined. That's what fflush() is for.
    Using fflush on an input stream (such as stdin) is undefined and should never ever be done.

    If you need a better way to deal with your input problems, read this:
    STDIN pitfalls

    3) This sequence of instructions makes no sense:

    free(info);
    root = info;
    Definitely. You are de-allocating a region of memory and then setting another pointer to it, which cannot lead to anything good. You should perhaps get in the habit of setting all your free() pointers to NULL:
    Code:
    free(info);
    info = NULL;
    To limit the scale of such an wrong/accidental assignment and make it easier to debug.
    Last edited by MK27; 04-16-2010 at 08:28 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    4
    I was just able to do this assignment after my test was over.

    Quote Originally Posted by Overworked_PhD View Post
    You aren't correctly free()ing the memory. What you need is a post order traversal in order to free() the nodes on your tree.
    I tried creating a function like that, but it gives an error of info not initialized.

    Code:
    void sdestroy(STOCK *p)
    {
     if(p != NULL) {
      sdestroy(p->left);
      sdestroy(p->right);
    
      free(p);
     }
    }
    The assignment is mostly done. The problem I having now is the error occured after I modify(delete and add) a stock detail and tried to view it. I attached the code here.

    Of course, any advise to improve my code are welcome.

    @MK27,claudiu,Overworked_PhD
    Thanks for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. BST/Red and Black Tree
    By ghettoman in forum C++ Programming
    Replies: 0
    Last Post: 10-24-2001, 10:45 PM

Tags for this Thread