Home > Back-end >  Storing strings from pointers in Linked lists
Storing strings from pointers in Linked lists

Time:12-18

Recently started to practice linked lists. I am aware of the basic algorithm and concept and thought of implementing LL to store a bunch of strings which are input by the user.

But apparently I keep getting Segmentation fault.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _node{
    char *s;
    struct _node *next;
}
node;

int main()
{
    node *head = NULL;
    int a = 0;
    char ch;
    char *str = malloc(10);
    do
    {
        printf("\nDude %i:", a);
        fgets(str, 10, stdin);

        node *n = malloc(sizeof(node));
        if(n == NULL)
        {
            printf("\ninsufficient memory");
            return 1;
        }
        
        if(a == 0)
        {
            strcpy(n->s, str);
            n->next = NULL;
            head = n;
        }

        else
        {
            strcpy(n->s, str);
            n->next = head;
            head = n;
        }
        
        a  ;
        printf("\n continue?(y/n): ");
        scanf("\n%c", &ch);
        
    }while(ch == 'y');
    
    for(node *temp = head; temp != NULL; temp = temp -> next)
    {
        printf("\n%s", temp->s);
    }
    return 0;
}

I do understand that my logic/code is flawed somewhere since I am touching memory I should not touch but cannot seem to point out where since it is my first time dealing with linked lists.

CodePudding user response:

When you are malloc'ing space for the struct, you are only allocating space for the pointer to the string in your _node struct. You need to allocate some memory where you store the string and point the pointer s to it, before you do the strcpy. i.e.

n->s = malloc(sizeof(char)*100);

Remember that you also need to have a strategy to de-allocate this memory.

As the others hinted, these sort of errors are usually easily caught by looking/debugging with gdb. Remember that it's useful to compile with the -g flag to get useful debugging info.

CodePudding user response:

The reason you catch a ''Segmentation fault' is because you don't allocate memory for s variable of struct node before copying actual string: strcpy(n->s, str). So, allocate memory for s:

n->s = (char *) malloc(10 * sizeof(char));

CodePudding user response:

Note that you cannot write anything into an unallocated space, so you need to call malloc for the string in each node. If the string lengths are fixed, then you can specify the length in the definition of struct node to avoid the malloc problem.

Also, it is suggested to always free the objects that will no longer be referenced.

With a few revisions, the codes below may be helpful:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 10

typedef struct node {
    char str[LEN];
    struct node *next;
} Node;

int main() {
    Node *head = NULL;
    int n = 0;
    char c = 'y';
    while (c == 'y') {
        Node *node = malloc(sizeof(Node));
        printf("Node #%d: ", n);
        scanf(" ");

        /* Store the string directly into the node. */
        fgets(node->str, 10, stdin);
        /* Remove the newline character. */
        node->str[strcspn(node->str, "\n")] = 0;

        node->next = head;
        head = node;
          n;
        printf("Continue? (y/N): ");
        scanf("%c", &c);
    };

    Node *curr = head;
    while (curr != NULL) {
        printf("%s\n", curr->str);
        Node *temp = curr;
        curr = curr->next;

        /* Remember to free the memory. */
        free(temp);
    }

    return 0;
}
  • Related