I am fairly new to c (and this site) and I am having a lot of issues with segmentation faults. I am writing a program that creates a linked list of numbers and inserts values in ascending order.
void insert(struct element **head, struct element *new){
if((*head)->next == NULL && (*new).i > (*(*head)->next).i){
(*head)->next = new;
return;
}
if((*head)->next == NULL && (*new).i < (*(*head)->next).i){
new->next = (*head)->next;
*head = new;
return;
}
struct element *prev = *head;
struct element *current = (*head)->next;
while(current->next != NULL){
if((*new).i < (*current).i){
prev = current;
current = current->next;
} else if((*new).i > (*current).i){
new->next = current;
prev->next = new;
}
}
}
int main (void){
struct element **head;
int value;
printf("%s", "TEST" );
printf("%s" , "Please type in an integer value. ");
scanf("%d" , &value);
printf("%s", "TEST" );
do{
printf("%s", "TEST" );
struct element *new;
if((new = malloc(sizeof(struct element))) == NULL){
return(NULL);
}
printf("%s", "TEST" );
(*new).i = value;
printf("%s", "TEST" );
if(head == NULL){
*head = new;
printList(*head);
} else if(value <= 0){
printListBackwards(*head);
}
else {
insert(head, new);
printList(*head);
}
} while(value > 0);
I don't need help on whether the logic is correct with inserting or anything. I haven't even had a chance to really test it because I immediately get a segmentation fault after I enter an integer after the prompt. I know it seems funky, but the specs call for you to use a pointer to a pointer to a structure (the head of the linked list).
mainfunction. Also, before asking for help, make sure that your code doesn't show warnings/errors when compiling. Try compiling with the flags-Wall -Wextra. When figuring out segfaults I findvalgrindan extremely useful tool, give it a try. Just remember to compile with the-gflag to generate debugging symbols