Reputation: 13
I am new to C and have stumbled upon a problem I hope you can help me with.
We have a double linked list
struct LinkedList {
LinkedListNode *first;
LinkedListNode *last;
};
and the nodes which are elements therein
struct LinkedListNode {
LinkedListNode *previous;
LinkedListNode *next;
char *data;
};
Trying to append elements to the list, I wrote a function which creates a node at the end of the list with the given data.
void append(LinkedList *list, char *data)
It works properly if I call the function like this:
append(list, "abc");
append(list, "def");
Which leads to the linked list containing 2 nodes - the first one with data being "abc"
and the second one with data being "def"
.
However, if I pass the data as a variable, for example with
char testData[10] = "";
strcpy(testData, "abc");
append(list, testData);
strcpy(testData, "def");
append(list, testData);
The result is 2 linked list nodes both with the data "def"
.
The reason for it probably is that the data pointer inside the first and second node both point to the same memory, however, I don't know how to change this fact or how to circumvent it.
The code where I pass the data inside the function looks like this:
struct LinkedListNode *newNode = malloc(sizeof(struct LinkedListNode));
newNode->data = data;
I hope you can help me and thanks in advance.
Upvotes: 1
Views: 160
Reputation: 34585
The list is only storing a pointer to the data. In the first example those pointers to string literals are different, but in the second example, they all point to the same place, where the data is changing.
Perhaps you can try such as
char testData[10] = "";
strcpy(testData, "abc");
append(list, strdup(testData));
strcpy(testData, "def");
append(list, strdup(testData));
but remember that strdup
allocates memory which will need to be freed later.
An alternative is to duplicate the string within the function, though will create redundancy if a string is passed that is already unique.
newNode->data = strdup(data);
Although the function strdup
is in many libraries, it is non standard, but easy to create your own (thanks David Bowling).
Upvotes: 3