Alec Benson Alec Benson - 11 days ago 8
C Question

Why does this replace the initial values?

When I attempt to parse a text file and then print just the contents in a singly linked list, every value is for some reason overwritten by the second last value. For instance, if the list is

a

b

c

d

the code will print those proper lines inside of the while loop, but then when I try to print the heads string at the end of the code the code will only print d for both the head and the heads next value.

char buf[1024];
printf("Enter the file name: ");
fgets(buf, 1024, stdin);

char *file_name = strtok(buf, "\n");
FILE *fp;
fp = fopen(file_name2, "r");


char *throwaway = fgets(buf, 1024, fp);

struct bit_t *tail;
struct bit_t *head;
head = create_node(throwaway);
printf("%s\n", head->pos1);
int count;
count = 0;
//issue is that it is just overwriting the old results
while( (fgets(buf, 1024, fp)) != NULL ) {

printf("String : %s\n", buf);
tail = insert_tail(head, create_node(buf));

printf("%s\n", tail->pos1);
}
printf("Results : \n");
printf("%s\n", head->pos1);
printf("%s\n", head->next->pos1);

struct bit_t *create_node(char *pos1)

{
struct bit_t *r;
struct bit_t *current;

r = malloc(sizeof(struct bit_t));
if(!r) {
exit(1);
}
r->next = NULL;
r->pos1 = pos1;
current = r;

return current;

}

struct bit_t *insert_head(struct bit_t *head, struct bit_t *node)
{
node->next = head;
head = node;
return node;
}
struct bit_t *insert_tail(struct bit_t *head, struct bit_t *node)
{
struct bit_t *current;
current = head;
while(current->next != NULL) {
current = current->next;
}
current->next = node;

return node;;
}


The structure begin used is

struct bit_t {
char *pos1;

struct bit_t *next;
};

Answer

Each element in your list points to buf but each iteration through your loop overwrites the contents of buf. To resolve the problem, each element needs to allocate storage space for the contents of buf and then copy the value of buf.