i'm having a problem in this code. its function is to go through a BST of strings and delete the nodes that satisfy some conditions (if in the word in the node there's an instance of the banned character, the node needs to be deleted). the problem is that it seg-faults in scrematurabanned2
because in the last recursive call it tries to access a node that is not existant and seg-faults. how can i fix this?
sorry in advance if there's not a lot of code in this question but this is a huge program and these are the parts that i think are responsible for the problem
struct node {
char *value;
struct node *p_left;
struct node *p_right;
};
int CmpStr(const char *a, const char *b)
{
return (strcmp (a, b));
}
void inserisciInAlbero2(char* key, struct node** leaf, Compare cmp) {
int res;
if( *leaf == NULL ) {
*leaf = (struct node*) malloc(sizeof( struct node ) );
(*leaf)->value = malloc( strlen (key) +1 );
strcpy ((*leaf)->value, key);
(*leaf)->p_left = NULL;
(*leaf)->p_right = NULL;
} else {
res = cmp (key, (*leaf)->value);
if( res < 0)
inserisciInAlbero2( key, &(*leaf)->p_left, cmp);
else if( res > 0)
inserisciInAlbero2( key, &(*leaf)->p_right, cmp);
}
}
void scrematurabanned2(struct node *head, const char *bannedchar, int n){
if( head != NULL ) {
scrematurabanned2(head->p_left, bannedchar, n);
if(strpbrk(head->value,bannedchar)!=NULL)
{
head = deleteNode(head, head->value);
}
scrematurabanned2(head->p_right, bannedchar, n);
}
}
struct node * minValueNode(struct node* node) {
struct node* current = node;
while (current->p_left != NULL)
current = current->p_left;
return current;
}
struct node* deleteNode(struct node* root, char *key) {
if (root == NULL)
return root;
int cmp_result = strcmp(key, root->value);
if (cmp_result < 0)
root->p_left= deleteNode(root->p_left, key);
else if (cmp_result>0)
root->p_right= deleteNode(root->p_right, key);
else{
if (root->p_left==NULL) {
struct node *temp = root->p_right;
free(root);
return temp;
} else if(root->p_right==NULL){
struct node *temp = root->p_left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->p_right);
strcpy(root->value, temp->value);
}
return root;
}
int main() {
struct node *BST = NULL;
inserisciInAlbero2("2rj9R", &BST, (Compare) CmpStr);
inserisciInAlbero2("2rF9d", &BST, (Compare) CmpStr);
inserisciInAlbero2("2rq9R", &BST, (Compare) CmpStr);
inserisciInAlbero2("2ft9R", &BST, (Compare) CmpStr);
scrematurabanned2(BST, 'r', 5));