The folowing program is intended to store words alphabetically in the Binary Search Tree using the strcmp function. The issue, detailed under the program, is that no pointer is passed in the recursive call of the function in the last part of the function.
typedef struct NodT{
char word[30];
struct NodT *left, *right;
} NOD;
void reset_field(NOD *nod){
int i;
for(i=0; i<30; i++){
nod->word[i]='\0';
}
}
void enter_recursively(NOD *nod, char *word){
if(nod==NULL){
nod= (NOD *) malloc(sizeof(NOD));
nod->left=NULL;
nod->right=NULL;
reset_field(nod);
strcpy(nod->word, word);
return;
}
if(nod->word[0]=='\0'){
strcpy(nod->word, word);
return;
}
if(strcmp(nod->word, word)==0) return;
if(strcmp(nod->word, word)<0){
enter_recursively(nod->right, word);//the problem seems to be here
printf("right\n");
}
else{
enter_recursively(nod->left, word);//...and here
printf("left\n");
}
//the NULL pointer is being sent over, which is peculiar
}
The thing is that, when I pass the pointers(left, right) from the structure to the recursive function in the if-else conditions, it takes a NULL value on the other side, which it shouldn't do because they are not NULL after alocating the first word in the root and the second in the right or left depending on strcmp, alocation when malloc is used to create the new storage space for the word.
UPDATE: The new script using double pointers:
typedef struct NodT{
int key;
char word[30];
struct NodT *left, *right;
} NOD;
void enter_recursively(NOD **nod, char *word){
printf("N: %p\n", nod);
printf("NL: %p\n", (**nod).left);
printf("NR: %p\n", (**nod).right);
if(nod==NULL){
nod=malloc(sizeof(NOD));
(**nod).left=NULL;
(**nod).right=NULL;
strcpy((**nod).word, word);
return;
}
if((**nod).word[0]=='\0'){
strcpy((**nod).word, word);
return;
}
if(strcmp((**nod).word, word)==0) return;
if(strcmp((**nod).word, word)<0){
enter_recursively((**nod).right, word);
}
else{
enter_recursively((**nod).left, word);
}
I get segmentation fault and I don't know why.
nod == NULL
(or justnod
:) before you ever try to access its contents. You are probably just dumping your stack with these accesses. – Jens Gustedtreturn;
in a non-void function which makes no sense. Also your fistNULL
check will never match, you'll segfault before that ifnod
is null at function entry. – Matfor (i = 0; i < 30; i++) { nod->word[0] = '\0'; }
makes no sense. – pmg