Error in your code: Address assignment for newNode->Data->FName becomes invalid when you call free(input) in the processFile () function, and accessing free memory calls "Undefined Behavior" at runtime.
To fix your code:
instead of a simple assignment, for example:
newNode->Data->FName = strtok(input," ");
Select and copy to separate memory as shown below:
char *ptr = strtok(input," "); newNode->Data->FName = malloc(strlen(ptr)+1); strcpy(newNode->Data->FName, ptr);
In fact, you assigned a memory address from the input address space to addOrdered () and execute the free() function in processFile() .
I will explain your code in more detail below:
First read: char * strtok (char * str, const char * delimiters); manual:
When the function is called for the first time, it expects the string C as an argument to str, the first character of which is used as the source for scanning tokens. In subsequent calls, the function expects a null pointer and uses the position immediately after the end of the last token as a new start location for scanning.
Return value
Pointer to the last token found in the string. Returns a null pointer if there are no tokens to return.
It does not send new memory, but the memory from input that you recently freed (). To understand the function of strtok (), I wrote the following code:
int main (){ char str[] ="- This, a sample string."; printf("str address: %p, ends on: %p \n", str, str+strlen(str)); printf ("Splitting string \"%s\" into tokens:\n",str); char * pch; pch = strtok (str," ,.-"); while (pch != NULL){ printf ("pch: %7s, address: %p\n",pch, pch); pch = strtok (NULL, " ,.-"); } return 0; }
Execution of the above program (the address may be different each time you start):
~$ ./a.out str address: 0x7fff96958d50, ends on: 0x7fff96958d68 Splitting string "- This, a sample string." into tokens: pch: This, address: 0x7fff96958d52 pch: a, address: 0x7fff96958d58 pch: sample, address: 0x7fff96958d5a pch: string, address: 0x7fff96958d61
Note. The pch address is in / within str .
Similarly, in your code, assign the function newNode->Data->FName = strtok(input," "); in addOrdered() . the value of the memory address in newNode->Data->FName is in / from input , which you later release in the processFile() function So newNode->Data->FName becomes invalid, and your code works as undefined behavior
void addOrdered(Node ** Head,char * input){ printf("\nInput: %s\n",input); // some code here step-2 newNode->Data->FName = strtok(input," "); <--"assign memory" ^ // Some code here | } | | void processFile(Node ** Head, FILE * fd){ | step-1 char * input = malloc(sizeof(char)*SIZE); <-|----"Allocate memory" while(fgets(input,SIZE,fd) != NULL){ | addOrdered(Head,input); ----------------- } step-3 free(input); <-----------------------------------"Free memory" } So, "What is assign to newNode->Data->FName becomes invalid"
Second , you must read one less char from the file in the buffer, save a space for null \0 .
fgets(input, SIZE-1, fd)