Search code examples
clinked-listabstract-data-type

C memory allocation for linked list


I'm trying to make an Linked List that essentially holds a string (rather than a character array). I keep getting segmentation fault (core dumped) and I'm not sure where/how I'm allocating memory wrong

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

struct mystring
{
    char letter;
    int size;
    int isHead;
    struct mystring*next;
};

struct mystring * create_empty_string(int size)
{   
    struct mystring * string = malloc(sizeof(struct mystring));
    string->size = size;
    string->isHead = 0;
    return string
}

struct mystring * make_string(struct mystring * list,char * string)
{ 
    for(int i = 0 ; i < strlen(string) ; i++)
    {
        list->letter= string[i];
        list = list->next;
    }
    return list;
}
void printList(struct mystring* list) {

   //start from the beginning
   while(list->letter != '\0') {
      printf("(%c) ",list->letter);
      list = list->next;
   }
}
int main()
{
    struct mystring * string = create_empty_string(10);
    string = make_string(string, "hey");
    printList(string);
}

Solution

  • As noted, your create_empty_string() function is poorly constructed. I suggest building the linked list one node at a time by feeding individual characters into a function called append_to_string() or similar, which will create a new node and link it to the previously constructed list (or become the list itself if it's the first node).