Allocating a struct and saving a string in it

78 views Asked by At

I'm having issues with getting create to hold firstE here:

struct node {
    char * data;
    struct node * next;
};

struct node * createList(char * firstE){
  struct node *create;

  create = malloc(sizeof(struct node));
  create->data = malloc(sizeof(struct node));
  strcpy(create->data, firstE);
  create->next = NULL;
  return create;
}

I'm having a problem with the memory allocation for create->data. I am trying to get it to hold the value of FirstE but I can't seem to get it.

1

There are 1 answers

3
Weather Vane On

I have to guess your problem since there is no struct definition. Your second malloc allocates memory for a field of the same type as the struct. But because you use strcpy to copy from the function argument, I suggest this line is incorrect, it allocates the wrong amount of memory

create->data = malloc(sizeof(struct node));
strcpy(create->data, firstE);

Since you copy the string argument to this field, I suggest this

create->data = malloc(1 + strlen(firstE));
strcpy(create->data, firstE);

The 1 + is to allow for the string terminator.