Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Properly Allocating Memory for Doubly Linked List Node Struct with String Data

I'm trying to create a function to dynamically allocate memory for new nodes in a doubly linked list that have strings as data members.

The function is supposed to dynamically allocate memory for new nodes based on the number of characters that will be stored in their string data members. So far I have this:

// Size is the number of characters for the string data member
struct list_node_s* Allocate_node(int size) {

  int nodeSize = sizeof(struct list_node_s);
  int stringSize = size * sizeof(char);

  return (struct list_node_s*)malloc(nodeSize + stringSize);

} 

And here's the node struct being pointed to:

struct list_node_s {
   char*  data; //char array where string data member is stored
   struct list_node_s* prev_p;
   struct list_node_s* next_p;
};

EDIT: Here's my insert function:

void Insert(struct list_s* list_p, char string[]) {
//   Initializes new node to be inserted
   struct list_node_s* newNode = Allocate_node(strlen(string) + 1);
   if (newNode == NULL){
      printf("Error allocating new node!\n");
      return;
   }
   newNode->data = string;
   newNode->next_p = NULL;

//   Makes new node both head and tail if list is empty
   if (list_p->h_p == NULL) {
      printf("Inserting into empty list\n");
      list_p->h_p = newNode;
      list_p->t_p = newNode;
      list_p->h_p->prev_p = NULL;
      printf("New head data: %s\n", list_p->h_p->data);
      return;
   }
//   Inserts new node as new head if new string is less than head's data
   if (strcmp(newNode->data, list_p->h_p->data) < 0) {
      printf("Inserting as new head\n");
      newNode->prev_p = NULL;
      list_p->h_p->prev_p = newNode;
      newNode->next_p = list_p->h_p;
      list_p->h_p = newNode;
      return;
   }
//   Inserts new node as new tail if new string is greater than tail's data
   if (strcmp(newNode->data, list_p->t_p->data) > 0) {
      printf("Inserting as new tail\n");
      newNode->prev_p = list_p->t_p;
      list_p->t_p->next_p = newNode;
      list_p->t_p = newNode;
      return;
   }
   printf("Iterating thru list\n");
   struct list_node_s* temp = list_p->h_p->next_p;
   printf("Starting node: %s", temp->data);
   while (strcmp(temp->data, newNode->data) < 0) {
      temp = temp->next_p;
   }
   (temp->prev_p)->next_p = newNode;
   newNode->prev_p = temp->prev_p;
   temp->prev_p = newNode;
   newNode->next_p = temp;
}

This works for adding a single node to the list but gives me a segfault if I add any more. Am I allocating enough memory here?

Comments