简体   繁体   中英

Why is realloc overwriting strings?

I'm trying to write a program that dynamically increases a char array. When I print the array, it increments the array, but old data is overwritten with whatever the user inputs and duplicates that input each time. Can someone please help me?

Desired output:

Item1
Item2
Item3

Current output:

Item3
Item3
Item3

Here is my code:

int main()
{
    int length = 1;
    char *list;
    list = calloc(length, length * sizeof(char *));

    char *temp;
    char user_input[100];

    while (1) {
        fgets(user_input, 100, stdin);
        user_input[strcspn(user_input, "\n")] = 0;

        temp = realloc(list, length * sizeof(char));

        strcpy(temp, user_input);

        list = temp;

        printf("****LIST****\n\n");
        for (int item = 0; item < length; item++) {
            puts(list);
        }
        printf("\n");

        length++;
    }
    return 0;
}

list should be char ** since it's an array of strings, not a single string.

You need to allocate a separate string for each list item, to hold a copy of that line.

int main()
{
  int length = 0;
  char **list = NULL;

  char user_input[100];

  while(1)
  {
    fgets(user_input,sizeof user_input,stdin);
    user_input[strcspn(user_input,"\n")] = 0;

    char *temp = malloc(strlen(user_input) + 1);
    if (!temp) {
        printf("Unable to allocate input string\n");
        exit(1);
    }
    strcpy(temp,user_input);

    length++;
    char **temp_list = realloc(list, length * sizeof(*temp_list));
    if (!temp_list) {
        printf("Unable to realloc list\n");
        exit(1);
    }
    list = temp_list;
    list[length-1] = temp;

    printf("****LIST****\n\n");
    for(int item = 0;item < length;item++)
    {
      printf("%s\n", list[item]);
    }
    printf("\n");

  }
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM