i have this code trying to read a word from a list of words stored in a .txt file
char *getWord(char *filename) {
char formatstr[15], *word;
static FILE *input;
static int firstTime = 1;
if (firstTime) {
input = fopen(filename, "r");
if (input == NULL) {
printf("ERROR: Could not open file \"%s\"\n", filename);
exit(1);
}
firstTime = 0;
}
word = (char*)malloc(sizeof(char)*WORDLEN);
if (word == NULL) {
printf("ERROR: Memory allocation error in getWord\n");
exit(1);
}
sprintf(formatstr, "%%%ds", WORDLEN-1);
fscanf(input, formatstr, word);
if (feof(input)) {
fclose(input);
return NULL;
}
return word;
}
And then this code to try and store it into a linked list
struct num1* wdStr(int wdLength, char *filename)
{
int d; // total words.
char *wordC;
struct num1 *head = NULL;
struct num1 *temp;
d = edCount(filename);
for(int i = 0; i < d; i++)
{
wordC = getWord(filename);
if(strlen(wordC) == wdLength)
{
temp = (struct num1*)malloc(sizeof(struct num1));
temp->val = wordC;
temp->next = head;
head = temp;
}
}
//return head;
}
edCount just counts how many words are there.
So after running the program, always before the last word i get a "Segmentation fault (core dumped)" error. I know i am doing something wrong with the pointers but still i cant find what.