I can't figure out what is wrong with this function.
I have tried multiple input files, but with every one the last node is corrupt.
I'm certain it is not the input file because I printed out the "input" before the last node is added to the linked list.
Someone please see if they can see why this code is not working correclty.
All other nodes are valid and correct.
Thank you John and Ritchie.
I am so grateful for the quick replies and the solution to my problem.
My forehead and display are also very grateful.
I haven't really written any code since college and the information you've shared is huge - this is my first LL since then.
Ritchie hit on the first bug that killed me, I kept getting "only" the last record from the input file until I realized I had to allocate a new block of memory to "input" for each node as it is pulled out of the file and then passed to "ptr" (which I think I will rename "tail" for clarity). Then I started getting all my nodes but the last was corrupt. So to make sure I understand the solution correctly (I believe just making code work is not the full solution if you don't understand why it works).
I should free "input" since it is allocated but unused at the end of the program. That way it is returned to the heap and does not create a memory leak eating up my RAM.
"ptr" however is still being used for the last node in my linked list, so when I free it, I corrupt my address to the memory location of my last node.
Do I understand the solution correctly?
Yay and thank you again!
Now I need to convert it to a double linked list.
Lancelot Link wrote:Do I understand the solution correctly?
Yes, if I understand you correctly
Allocate input memory inside the loop before doing the fread(). Then you don't need 2 input malloc()s.
The ptr malloc - I think that is a bug, you shouldn't be doing that. I guess that's why you added the free(ptr) at the end. ptr should just be pointing to the last record, but input is where you malloc() the memory.
Use sizeof(*input) instead of sizeof(struct Record) to make the code independent of input's type.
You can use a double-pointer to avoid having the special case for the empty list. That is, input is a Record**, which initially points to &head, but subsequently points to the &next of the last record read in. Then you don't need the 'if' inside the for() loop. I'll write some code later if you like and I get time, but you could try it yourself.