I have a function in C that should create 3 nodes for a linked list. The problem is that the function seems to be adding an extra node and I cannot spot my error. Can someone take a look at the output and code and let me know what my error is? Can the problem be with the virtual machine compile environment? I'm compiling with the following code in a virtual machine running BackTrack Linux:
gcc link.c -o link
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DELIMITER ,
struct node {
int data;
struct node *next;
};
struct node* create()
{
//define head pointers
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
//allocate memory
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
//setup fields
//assign links
head->data = 15;
head->next = second;
second->data = 20;
second->next = third;
third->data = 25;
third->next = NULL;
return head;
}
int main(int argc, const char *argv[])
{
int size;
struct node *head;
head = create();
struct node *curr = head;
while(curr->next != NULL)
{
printf("%d\n", curr->data);
curr++;
}
return 0;
}
this is the output:
15 0 20 0