wendy
wendy

Reputation: 21

add pointer elements to linked list

Is there possible to make the code work without changing the main function? I have tried using strcpy() in the push function but it results in segmentation fault (core dumped).
This is the output currently:

ccc ccc ccc
ccc ccc ccc
ccc ccc ccc

The output should be

ccc ccc ccc
bbb bbb bbb
aaa aaa aaa  

Code:

struct Node
    {
        char *data1;
        char *data2;
        char *data3;
        struct Node *next;
    };

   int main()
   {
       struct Node *head = NULL;
       char strings[3][10];
       char *s = "aaa";
       for (int i = 0; i < 3; i++)
       {
           strcpy(strings[i], s);
       }
       push(&head, strings);
       s = "bbb";
       for (int i = 0; i < 3; i++)
       {
           strcpy(strings[i], s);
       }
       push(&head, strings);
       s = "ccc";
       for (int i = 0; i < 3; i++)
       {
           strcpy(strings[i], s);
       }
       push(&head, strings);
   
       printList(head);
       freeList(&head);
   }

void push(struct Node **head_ref, char new_data[3][10])
{
   /* 1. allocate node */
   struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));

   /* 2. put in the data  */
   new_node->data1 = new_data[0];
   new_node->data2 = new_data[1];
   new_node->data3 = new_data[2];

   /* 3. Make next of new node as head */
   new_node->next = (*head_ref);

   /* 4. move the head to point to the new node */
   (*head_ref) = new_node;
}

Upvotes: 2

Views: 81

Answers (2)

machine_1
machine_1

Reputation: 4454

The problem in your code is that the pointers of the allocated nodes are all pointing to the same 3 memory locations: strings[0], strings[1], and strings[2].

The statements:

new_node->data1 = new_data[0];
new_node->data2 = new_data[1];
new_node->data3 = new_data[2];

do not copy the strings to data1, data2, and data3 but rather store the memory addresses in them.

If you want to copy the strings contained in new_data[0], new_data[1], and new_data[2], you should allocate memory to data1, data2, and data3 and use the function strcpy() to do it.

example:

new_node->data1 = malloc(strlen(new_data[0]) + 1);
new_node->data2 = malloc(strlen(new_data[1]) + 1);
new_node->data3 = malloc(strlen(new_data[2]) + 1);

strcpy(new_node->data1, new_data[0]);
strcpy(new_node->data2, new_data[1]);
strcpy(new_node->data3, new_data[2]);

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You are using the same strings over and over. You must allocate (in push) new arrays for each string. For example:

new_node->data1 = malloc(10);
new_node->data2 = malloc(10);
new_node->data3 = malloc(10);

strcpy(new_node->data1, new_data[0]);
strcpy(new_node->data2, new_data[1]);
strcpy(new_node->data3, new_data[2]);

Upvotes: 3

Related Questions