why am I getting out of bounds error in this linked list? C -


so making linked list. printing out. , reversing it. , printing out. first time make , print out. works fine. when reverse it. reverses successfully. when print it. go out of bounds though use same code did first.

here reverse function

void reverse_list(node_ptr* head){  node_ptr temp2; node_ptr temp3 = null; temp2 = (node_ptr)malloc(sizeof(node)); temp3 = (node_ptr)malloc(sizeof(node));  if (temp2==null || temp3==null) {     printf("failed allocate node\n");     exit(1); }  while (*head!=null) {      temp2 = (*head)->next;     (*head)->next = temp3;     temp3 = (*head);     (*head) = temp2; }  *head = temp3; 

}

here print function

temp = head; while (temp != null) {     printf("%d\n", temp->data);     temp = temp->next; }  reverse_list(&head);  temp = head;  while (temp != null) {     printf("%d\n", temp->data);     temp = temp->next; } 

for reason tries print garbage after last element

do this:

/* function reverse linked list */ void reverse(struct node** head_ref) {     struct node* prev   = null;     struct node* current = *head_ref;     struct node* next;      while (current != null)     {         next  = current->next;           current->next = prev;            prev = current;         current = next;     }      *head_ref = prev; } 

it's code couple of fixtures, i.e.:

1) don't need allocate space, swap pointers.

2) use meaningful names temporary containers.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -