Why does it iterate one more time even if it is NULL?

119 Views Asked by At

Similar question here . What I want to understand is that when current_node is NULL, the compiler doesn't see it as NULL and iterates one more time.

    void printBranches(struct bank *head) {
    struct branch *current_node = head->branches;
    while (current_node != NULL) {
        printf("%s ", current_node->bname);

        current_node = current_node->nextb;
    }
}

This is my print function.

Even though I use current_node!=NULL condition it prints something like this:' ╨q%+☺ ' when it is supposed to be NULL which I assume that it points somewhere unused in the memory(that has no meaningful value inside of it). Here my debugger shows addresses it points;

 current_node 0x27e6b5d1740 when it is not NULL

              0x27e6b5d17f0 when it is suppose to be NULL
              0xbaadf00dbaadf00d when compiler sees it as NULL

Any help would be appreciated. Thanks in advance.

Edit: I've realized that in the method I use for filling linked list's node after determining the name of the node I immediately create a new node in the memory and then go to next without setting it to NULL as @trincot mentioned in the comments.

  memcpy(new_branch->bname, entity, sizeof(entity));

        // Go next branch
        new_branch->nextb = malloc(sizeof(struct branch));
        new_branch = new_branch->nextb;

That's why the last non-filled node is not empty.

Edit 2: When I do what @trincot said in the comments I can not add a new node after the first node. So I've tried a different method.

while (current_node->nextb->nextb != NULL) {
    printf("%s ", current_node->bname);

    current_node = current_node->nextb;
}

when I do this problem is solved because I can print what I want without meaningless value.

0

There are 0 best solutions below