c - Linked list prints extra 0 at the beginning -
i have basic singly linked list implementation. problem implementation, however, prints 0 @ beginning of list whereas not explicitly allocating storage node. code same below -
#include <stdio.h> #include <stdlib.h> #include <assert.h> #define len 7 /* list node data structure */ typedef struct _ll_node_ { int data; struct _ll_node_ *next; } node; /* * @brief utility print state of list */ void print_list(node *head) { int = 0; node *tmp = head; while (tmp) { printf("node:\t%d,\tvalue:\t%d\n", ++i, tmp->data); tmp = tmp->next; } printf("\n"); } /* * @brief utility add nodes list */ node *add_node(node *head, int data) { node *tmp; if (head == null) { head = malloc(sizeof(node)); assert(head != null); head->data = data; head->next = null; } else { tmp = head; while (tmp->next) tmp = tmp->next; tmp->next = malloc(sizeof(node)); assert(tmp->next != null); tmp = tmp->next; tmp->data = data; tmp->next = null; } return head; } /* * @brief driver function */ int main(int argc, char *argv[]) { node *head = null; int = 0; /* allocate memory */ head = malloc(len * sizeof(node)); assert(head != null); /* populate list */ (; < len; i++) head = add_node(head, rand() % 1000); /* print state */ print_list(head); return 0; }
can please me figure out doing wrong?
system information: distributor id: ubuntu description: ubuntu 14.04.3 lts release: 14.04 codename: trusty
this statement
head = malloc(len * sizeof(node));
does not make sense. remove it.
you allocated uninitialized array. using function add_node results in undefined behaviuor.
take account function add_node
written simpler if pass head reference. example
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <time.h> #define len 7 /* list node data structure */ typedef struct _ll_node_ { int data; struct _ll_node_ *next; } node; /* * @brief utility print state of list */ void print_list(node *head) { int = 0; node *tmp = head; while (tmp) { printf("node:\t%d,\tvalue:\t%d\n", ++i, tmp->data); tmp = tmp->next; } printf("\n"); } /* * @brief utility add nodes list */ int add_node( node **head, int data ) { int success; while ( *head != null ) head = &( *head )->next; *head = malloc( sizeof( node ) ); success = *head != null; if (success ) { ( *head )->data = data; ( *head )->next = null; } return success; } /* * @brief driver function */ int main( void ) { node *head = null; int = 0; srand( ( unsigned int )time( null ) ); /* populate list */ ( ; < len; i++ ) add_node( &head, rand() % 1000); /* print state */ print_list( head ); return 0; }
Comments
Post a Comment