0

I am quite confused about malloc in struct. I create a linked list with both head and tail. Each node have a pointer point to a string, and a pointer point to the next node:

struct node {
    char* string;
    struct node_t* next;
}
struct linkedlist {
    struct node* head;
    struct node* tail;
};

When initialise them, do I need to malloc all of list, node and string at first? Or only need to malloc some of them? And what would be the difference if I only set them to NULL without malloc? And where would be an appropriate place to malloc them? For example, at make_linkedlist function, do I also malloc head and tail directly after malloc list? Or I can set them to NULL first, then malloc at create_node function? What about string? Do I need to also malloc space for it? If I would only assign the string pointer to another string pointer, do I write:

string = (char*)malloc(sizeof(char) * size);

or

*string = "";

or

*string = NULL:

?

Thanks a lot if anybody can help!

Emmm
  • 13
  • 3
  • See this question: [When and why to use malloc?](https://stackoverflow.com/questions/8800482/when-and-why-to-use-malloc) – Ruks Apr 09 '20 at 13:54
  • Your struct needs to exist in a place in memory, and the pointer must point to a valid place in memory or to NULL. Exactly how this structs will be created (do they live as global variables, or live inside a single function, or are retrieved from an array or pool of structs, or are created using `malloc`) is basically your choice. – Groo Apr 09 '20 at 14:03
  • @Emmm See my answer at this reference https://stackoverflow.com/questions/61116597/fix-for-a-reversed-link/61119253#61119253 There is an example of a linked list. To store a string in the list you need to allocate memory for it that will be pointed to by the data member string of your structure definition. Also you will need to define a function that will free all allocated memory. – Vlad from Moscow Apr 09 '20 at 14:04
  • The first result on Google is the duplicate. Search before posting. – S.S. Anne Apr 09 '20 at 14:30

0 Answers0