I have a function to read a load of words from a file and store them in a linked list. The struct for which is:
typedef struct node {
char * word;
int wordLength;
int level;
struct node * parent;
struct node * next;
} Node;
In this function, I have Start->word and Current->word pointing to the first word in the list. Then, cycle through the rest of the words in the file, storing them into Current. I want to keep Start, pointing to the start of the list, but, when I print out the value of Start->word at the end of the function, it's value has changed to the last word in the file stream. This code works fine if I statically assign the max length of Node->word and currentWord, however, the code is meant to make no assumptions about the maximum word length. Here is the funciton:
Node * GetWords(char * dictionary, Node * Current, int * listLength, int maxWordLength)
{
Node * Start = (Node *)malloc(sizeof(Node));
FILE *fp;
char * currentWord = (char *)malloc(maxWordLength * sizeof(char));
fp = fopen(dictionary, "r");
ErrorCheckFile(fp);
if((fscanf(fp, "%s", currentWord)) != EOF){
Current = Start = AllocateWords(currentWord);
}
//If I print out the value of "Start" here, it is correct.
while((fscanf(fp, "%s", currentWord)) != EOF){
Current->next = AllocateWords(currentWord);
Current = Current->next;
(*listLength)++;
}
printf("Starting: %s\n", Start->word); //If I print out the value of
//"Start" here, it is set to the same value as "Current", which is the
//last word in the file. I need to keep "Start" constantly pointing to
// the start to I can reset "Current" to the start throughout the program.
fclose(fp);
return Start;
}
Here is my AllocateWords():
Node * AllocateWords(char * string)
{
Node * p;
p = (Node *)malloc(sizeof(Node));
if(p == NULL){
fprintf(stderr, "ERROR: Cannot allocate space...\n\n");
exit(1);
}
p->word = string;
p->level = -1;
p->parent = NULL;
p->wordLength = strlen(p->word);
p->next = NULL;
return p;
}