I was trying to create a single linked list that contains some words from a .txt file on my desktop, but when I run it in terminal, I got a segmentation fault. Later I compiled the code on Xcode and run it, I got this error message: Thread 1:EXC_BAD_ACCESS(code=1, address=0x7fff5fc00000) I'm a beginner, and I really need some help now. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct word{
int num;
char word[50];
struct word *next;
} Word;
#define len sizeof(Word)
Word *create();
void print(Word *head);
int main()
{
Word *head;
head = create();
print(head);
return 0;
}
Word *create()
{
Word *head, *p1, *p2;
char word[50], c;
int i = 0;
FILE *fp = fopen("/Users/apple/Desktop/words", "r");
head = p1 = p2 = NULL;
while(fp != NULL){
i = 0;
p1 = (Word *)malloc(len);
//get the English word
while((c = fgetc(fp)) != '\n'){
word[i++] = c;
}
word[i] = '\0';
strcpy(p1->word, word);
p1->next = NULL;
if(head == NULL){
head = p1;
p2 = p1;
} else {
p2->next = p1;
p2 = p1;
}
p1 = p1->next;
}
return head;
}
void print(Word *head)
{
Word *p = head;
while(p != NULL){
printf("%s\n", p->word);
p = p->next;
}
}
And this is the content of the .txt file: