I am attempting to overcome my fear of linked lists since my confidence built after my last few posts. I have re-attempted an older algorithmic exercise I had done before (incompleted.) Now, I am confident it is complete, however, I'm thrown the usual segmentation fault
error. I wonder, if there is a way to understand what causes this issue in the code, I can rarely identify it (but I'm still novice.)
For example:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int DATA;
struct node* LINK;
} node;
void create(struct node* head, int item){
struct node* new;
new = (struct node*)malloc(sizeof(new));
if (new == NULL){
printf("Memory not Available");
}
new->DATA=item;
new->LINK = NULL;
if (head == NULL){
head = new;
}else {
struct node* temp;
temp = head;
while(temp->LINK != NULL){
temp = temp->LINK;
}
temp->LINK=new;
}
}
int main(){
node* former = NULL;
int itm = 7;
create(former, itm);
printf("%i", former->DATA);
return 0;
}
Will produce the segmentation fault.
The algorithm I am attempting:
The following algorithm creates a node and appends it at the end of the existing list. head is a pointer which holds the address of the header of the linked list and item is the value of the new node. NEW is a pointer which holds the address of the new node and temp is a temporary pointer.
Algorithm: CREATE (HEAD, ITEM)
1. [Create NEW node]
a) Allocate memory for NEW node.
b) IF NEW = NULL then Print: “Memory not Available” and Return
c) Set NEW→DATA = ITEM
d) Set NEW→LINK = NULL
2. [Whether List is empty, head is the content of HEADER]
If HEAD = NULL then Set HEAD = NEW
3. Else
a) Set Temp = HEAD
b) While Temp→LINK ≠ NULL do
Set Temp = Temp→LINK
[End of while]
c) Set Temp→LINK = NEW
[End of IF]
4. Return
Based on the suggested link I continue to get the same error:
void create(node** head, int item){
*head = NULL;
node* new;
new = (node*)malloc(sizeof(*new));
if (new == NULL){printf("Memory not Available");}
new->DATA=item;
new->LINK = NULL;
if (head == NULL){head = &new;}else {
node* temp;
temp = *head;
while(temp->LINK != NULL){
temp = temp->LINK;}
temp->LINK=new;}}
int main(){
node* former;
int itm = 7;
create(&former, itm);
printf("%i", former->DATA);
return 0;
}