Question

As part of an assignment that is now past due, I was to read a list of search terms from a text file and store these in memory for searching. I decided to use a linked list to store the terms and my implemenation of struct node (stored in myheader.h) looks like this:

 struct Node{
  char * term;
  int termLength;
  struct Node *next;};

To save the rootNode as the head of my list, I had a separate function for creating it called startList that is defined as such:

    struct Node * startList(char * sterm){
  struct Node * rootNode;
  rootNode=(struct Node *)malloc(sizeof(struct Node));
  assert(rootNode != NULL);
  memset(rootNode,0,sizeof(struct Node));
  rootNode->term=sterm;
  rootNode->termLength = strlen(sterm);
  rootNode->next=NULL;
  return rootNode;
}

This seems to work fine, the trouble arises when I try to add a new node onto this rootNode, which is supposed to be done with this function:

void insert_another_node( struct Node * headNode, char * sterm){
  struct Node * newNode = (struct Node *) malloc(sizeof(struct Node));
  newNode->term=sterm;
  newNode->next=NULL;
  newNode->termLength=strlen(sterm);
  while (headNode->next != NULL){
    headNode=headNode->next;}
  headNode->next=newNode;
}

These functions are all called in this for loop:

 while ((fgets(search_wrd,41,list)) != NULL){
   strtok(search_wrd, "\n");
   if (count==0){
     rootNode=startList(search_wrd);}
   else{
     insert_another_node(rootNode,search_wrd);}
 count++;
 }
 fclose(list);
 }

Say I am trying to store a list of planets in this list, the last planet being Neptune. The insert_another_node function will update the terms stored in ALL of the nodes to the most recent term (including the rootNode). The result is the right number of nodes, but they all store "Neptune" at someNode->term.

All of the insert to the end of a linked list implementations I've seen for a linked list in c follow my logic, so I can't understand how this weird update is happening let alone a way to fix it. Any help would be greatly appreciated!

Was it helpful?

Solution

You are just assigning sterm each time, all the assignments point to the same original buffer. You need to make a copy each time.

Use strdup like this:

rootNode->term=strdup(sterm)

and

 newNode->term= strdup(sterm);

OTHER TIPS

You need to allocate new memory for each sterm. If you reuse the same memory location they will all have the same value and if you change one you will change them all (because they are the same).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top