Question : B Tree

The following code crashes when I execute using "Ctrl + F5" in VS 2005.

However if I Debug "F5" and step in then it never crashes and I verified the local variables, all looks fine.
Why does it crash when I execute without debug (Ctrl + F5). The code crashes during 3rd iteration

Code: Inserting node to BST.



 
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
struct List
{
   int data;
   struct List *next;
};

struct tree *insertBST (struct tree *start, int data);

int main (int argc, char *argv[])
{
    struct tree *start = NULL;
	int num[] = {50, 68, 10};
	for (int i = 0; i < 3; i++ )
		start = insertBST (start,  num[i]);
	return 0;
}

struct tree *insertBST (struct tree *ptr, int data)
{

   if (ptr == NULL)
   {
      ptr = (tree *)malloc (sizeof (tree *));
	  if (ptr == NULL)
		  printf ("Out of Space ************\n");
	  ptr->data = data;
	  ptr->left = NULL;
	  ptr->right = NULL;
   }
   else 
   {
	   if (data <= ptr->data)
		   ptr->left = insertBST (ptr->left, data );
       else if(data > ptr->data)
		   ptr->right = insertBST (ptr->right, data);
   }
   return ptr;

}

Answer : B Tree

ptr = (tree *)malloc (sizeof (tree *));

Should that not be

ptr = (tree *)malloc (sizeof (tree));

Random Solutions  
 
programming4us programming4us