namarino - 8 months ago 49

C Question

I'm trying to print a linked list after having added a node. I have a dummy node to start the list

`Node **nodeArray;`

nodeArray = malloc(10 * sizeof(Node *));

int i;

for (i = 0; i < 10; i++) {

nodeArray[i] = malloc(sizeof(Node));

}

if (userChoice == 'a')

add(&nodeArray, setNumber);

void add(Node ***nodeArray, int setNumber) {

char userString[5];

printf("Please enter some data: ");

scanf("%s", userString);

Node *head = *nodeArray[setNumber]; /* head pointer to first element of array (dummy) */

Node *newNode = malloc(sizeof(Node)); /* new node to be added to array */

strncpy(newNode->data, userString, sizeof(newNode->data)); /* copies string entered by the user to data field of new node */

newNode->next = NULL; /* initializes next field of new node to NULL */

Node *tmp = head; /* pointer to head of list */

while (!tmp->next) {

tmp->next = newNode; /* inserts new node into array */

tmp = newNode; /* points head to newly added node */

}

tmp = head; /* points tmp back to head of list */

printf("List is: ");

while (tmp->next) {

printf("%s", (tmp->data));

tmp = tmp->next;

}

}

But when I print, I get an infinite loop printing out the data field of the newly added node. Terrible with linked lists....what am I doing wrong?

Answer Source

```
while (tmp->next) {
tmp->next = newNode; /* inserts new node into array */
tmp = newNode; /* points head to newly added node */
}
```

In this snippet you're losing the refrence to the next node, and just adding the newNode next to the head. For instance you have the following list:

```
[1]->[2]->[3]
```

And you want to push a new element into that list: [4], what happens when you execute your push function (the snippet above) is:

```
tmp = head; // tmp = [1]
while(tmp->next) {
tmp->next = newNode; // [1]->next = [4]
tmp = newNode; // tmp = [4]
}
```

So the next time '(tmp->next)' is evaluated it will be evaluated as: [4]->next and it will be NULL, breaking the loop. Your list will then be:

```
[1]->[4]
```

The other elements are lost because you don't have a reference pointing to them anymore, this is called a memory leak because you won't be able to free them later.

You could write your push function this way:

```
tmp = head;
while(tmp->next)
tmp = tmp->next;
tmp->next = newNode // Adds new node to the tail of the linked list
```