this one is not homework, it just the fact that i’ve been out of school for more than 20 years and I NEVER had to use linked lists for anything at all. So i’m out of my element here.
anyway, I have
struct Data_Struct {
char *Name;
char *Task;
char *Pos;
struct Data_Struct *Next;
};
typedef struct Data_Struct MyData;
Which is a pretty simple struct for a linked list.
As you can see the data is stored in char* and when I populate the list I copy the pointers there.
All is well. The problem begins when those pointers get overwritten and I lose the original data. I tried copying the data into local char* malloc’ed on every “list_add()” but I keep on either crashing or losing data.
Yes, I do allocate enough and yes, I do copy the data and check that it’s copied correctly. I tried with memcpy, strcpy, etc ,etc.
I’m out of things to try so my question is, how do I make sure that the data I will be adding to the list is local. how do I copy those char* going into the list into local variables.
while an explanation on how to do this and why my code is bad is OK, I prefer code with the explanation.
Thank you.
Jess.
You don’t want to “copy into local”, you want to do as you say you’ve done; allocate fresh memory using
malloc(), store the data there, and save the pointers in the list node.If you have it, you can use
strdup()to combine themalloc()+strcpy()into one call.It’s hard to understand under what circumstances you experience that the data is overwritten, what are you doing to the list node(s) that cause this?
A basic prepend ought to look like this, for your node definition:
Obviously this lacks error handling (
malloc()andstrdup()can both fail). Note that it’s a prepend, and that the new head of the list is returned.