0

I'm sure it's something obvious... but I've been at it for ages now and just can't spot the error of my ways, so hopefully some fresh eyes will nail it.

BOOLEAN init()
{
    struct list *foodList = (struct list*)malloc(sizeof(struct list));

    struct node *head = (struct node*)malloc(sizeof(struct node));
    head->data = NULL;
    head->next = NULL;

    foodList->head = head;


    if (NULL == foodList) {
        printf("List creation failed");
        return FALSE;
    }


    return TRUE;
}


void add_node(struct list *foods, struct food * newFood) {


    struct node *curr = foods->head;

    while (curr->next != NULL) {
        curr = curr->next;
    }

    curr->next = (struct node*)malloc(sizeof(struct node));
    curr->next->data = newFood;
     printf("%p\n", curr);
    curr->next->next = NULL;


    }

List is just a typical list struct, as is node.

What's happening is each node is getting created successfully (their addresses being 0x7fd1dac03ab0, 0x7fd1dac03ac0, etc.), but the node->next is returning 0x7fd1dac03960 on every node. Like I said, I'm sure I'm doing something painfully obvious here... But any help would be greatly appreciated.

Edward
  • 319
  • 4
  • 13
  • Just use one of the many existing linked list implementations. – John Zwinck May 28 '14 at 14:15
  • 1
    Where is `foods` defined in `init()` function, you have used it here: `if (NULL == foods)` – 0xF1 May 28 '14 at 14:16
  • 1
    [Don't cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also, you should check whether `foodList` is `NULL` *before* dereferencing it. – Eric Finn May 28 '14 at 14:18
  • 3
    Consider switching to a node-based list implementation, without a distinct `head`. Just represent the entire list as a pointer to the first node. And seriously consider how you expect the head to ever change when calling `add_node()`. – unwind May 28 '14 at 14:19
  • 1
    `init()` : it's work to only memory leak. and `if (NULL == foodList) {` : Too late. – BLUEPIXY May 28 '14 at 14:27

0 Answers0