0

I can't seem to find where the problem is in my code, i'm essentially storing character patterns, if an existing pattern is already present I'll store it in the duplicate node, otherwise it will shift to the regular pattern one. The problem starts when i have a duplicate, it should move to the duplicate node, but instead loops infinitely.

The binary tree struct: :

struct arbre{
    char id[10];
    int length;
    int token;
    int count;
    struct arbre *pattern;
    struct arbre *doublon;
};
typedef struct arbre *Arbre; 

The function to create and make new nodes

void ajouter(Arbre *a, char *tablettre, int length, int token){
    if(*a==NULL){
        *a=(Arbre)malloc(sizeof(struct arbre));
        strcpy((*a)->id, tablettre);
        //append((*a)->id,tablettre);
        //printf("%s",(*a)->id);
        (*a)->length = length;
        (*a)->token = token;
        (*a)->doublon=NULL;
        (*a)->pattern=NULL;
    }
    if (strcmp((*a)->id, tablettre) == 0){   /// The problem is here
        printf("%s",(*a)->doublon->id);
        printf(" and %s",tablettre);
        ajouter(&(*a)->doublon, tablettre, length, token);
    }
    if (strcmp((*a)->id, tablettre) != 0){
        ajouter(&(*a)->pattern, tablettre, length, token);

    }

}
9
  • 1
    If you enter that function with *a==NULL, what is content of doublon in printf("%s",(*a)->doublon->id);? Commented May 5, 2022 at 13:26
  • 2
    Also get rid of typedef struct arbre *Arbre; hiding pointer types with a typedefs only adds confusion. When I see Arbre I have absolutely no idea that is is a pointer. If I see struct arbre *, I know it's a pointer. Commented May 5, 2022 at 13:29
  • 2
    ... and thing s like *a=(Arbre)malloc(sizeof(struct arbre)); are terrible. Rather write (struct arbre*)malloc(sizeof(struct arbre)); or remove the cast alltogether and write *a = malloc(sizeof(struct arbre)); Commented May 5, 2022 at 13:31
  • 2
    Besides your issue with dereferencing a NULL pointer, how would you ever get out of your recursion once you pass *a==NULL? You will always find that id holds same content as tablettre as you just copied it there a few lines above. Then you will always call again. You mustn't go from if to if without an else Commented May 5, 2022 at 13:31
  • 1
    You should start learning how to use a debugger. Stepping through your code would immediately reveal that you will always get into second if after you entered the first one. That would have shown the issue withing seconds. Commented May 5, 2022 at 13:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.