I have a segmentation error in C -


i have segmentation error, maybe lot more after run it, can't check else because of that.

the program should work this:

  • when user types in 5 numbers, should print out in ascending order
  • if user enter number exit, remove original value
  • if user enter native value, print list backwards

this code far:

#include <stdio.h> #include <stdlib.h>  struct element { int i; struct element *next; };  void insert (struct element **head, struct element *new) {  struct element *temp; temp = *head;  while(temp->next != null) {     if((*head==null))     {     head = malloc(sizeof(struct element));     //temp->i = i;     temp->next = new;     new = temp;     }     else if(temp->i == new->i)     {         new = malloc(sizeof(struct element));         free(new);         //purge(&head,&new);      }     else if(temp->i < new->i)     {         temp->i = new->i;     }     else if(temp->i > new->i)     {         new = new->next;     } }  }  void purge (struct element *current, struct element *predecessor) {  predecessor->next = current -> next; free(current); }  void printlist (struct element *head)  { while(head) {     printf("%d", head -> i);     head = head->next; }  }  void printlistbackwards (struct element *ptr) { if(ptr == null) {     printf("list empty \n");     return; } if(ptr->next != null) {     printlistbackwards(ptr->next); } printf("print %p %p %d\n", ptr, ptr->next, ptr->i); }   int main() { int n = 0; int count = 5; printf("enter number: \n"); scanf("%d",&n); struct element *new; new = malloc(sizeof(struct element)); struct element *head = null; new->i = n; while(count!=0) {     insert(&head,new);     printlist(head);         count++; }  } 

in main() function, allocate , create 1 element malloc(); try add list 5 times. going cause confusion. should allocate node once each element add list.

struct element *head = null;  while (count!=0) {     printf("enter number: \n");     if (scanf("%d", &n) != 1)         break;     struct element *new = malloc(sizeof(struct element));     if (new == 0)         break;     new->i = n;     new->next = null;     insert(&head, new);     printlist(head);         count--; } 

note revised code checks result of both scanf() , malloc(). sets new element's next pointer null. , counts down rather up; use less memory.

i've not tested there (and are) other problems, work better (fix of problems, not of problems).

you need learn how use debugger, @ least enough stack trace know line of code causing crash.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -