Program Overflow: Troubleshooting Tips

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
ma12
Messages
2
Reaction score
0
my program is not working properly after taking values it gets overflow

#include<stdio.h>
#include<conio.h>

void insert(struct node**, int);
struct node *ptr;

struct node
{
int data;
struct node *right;
struct node *left;
};


void main()
{
int will , i , num;
ptr = NULL;
ptr -> data = NULL;
printf("Enter the Number");
scanf("%d", &will);

for(i=0; i<will; i++)

{
printf("Enter the Item",&num);
insert(&ptr, num);
}
getche();
}



void insert(struct node **p, int num)
{

if( (*p) == NULL)
{
printf("Leaf node created");
(*p) -> left = NULL;
(*p) -> right = NULL;
(*p) -> data = num;
return;
}
else
{
if( num==(*p) -> data)
printf("Entered repeated values rejected");
return;
}

if(num < (*p) -> data)
{
printf("directed to left ");
insert ( &((*p) -> left) ,num);
}
else
{
printf("Directed to right");
insert( &((*p) -> right), num);
}


return;
}
 
Physics news on Phys.org
in void insert

if(num < (*p) -> data)
{
printf("directed to left ");
insert ( &((*p) -> left) ,num);
}
else
{
printf("Directed to right");
insert( &((*p) -> right), num);
}
 
What does p point to?

And if you think the answer is "struct node", check out your code.
 
Overflow probably means stack overflow. This usually means you got into an infinite recursion loop. In your code this is possible if you got into a situation where *p is never equal to NULL in insert(). If this happened insert() would keep calling itself forever, every call to insert() pushes a frame on the stack, eventually the stack overflows. One reason this might have happened is if you built a tree incorrectly such that there is a loop in it.

Also roger is right, if you ever somehow DID get to your "leaf node created" termination condition you'd instantly crash. You establish *p is NULL, then you assign to *p->left. If you write to or read from a null pointer you will crash (but the crash probably would not describe itself as an "overflow").