我在主函数中使用malloc和realloc创建一个字符串,每当用户键入一个字符时,该字符串都会增加一个字节。但是,当字符串达到length = 15时,似乎
停止分配空间,而不阅读我的错误消息?最终
大约20个字符后,它崩溃了。是因为我没有释放数据吗?否则有人可以告诉我这是什么问题吗?

int main()
{

  int loop = 1;
  int count = -1;
  int space_wanted;

  char * res;
  char * orig;
  char c;


  res = malloc(1);

  printf("Instructions: type q to quit. Continually type characters to add"
    " it to the string.\n");

  while (loop)
  {
    if ((c = fgetc(stdin)) != EOF && c != '\n')
    {
      if (c != 'q')
      {
        orig = res;

        /* One space for the new character and also for the
        null character */

        space_wanted = strlen(orig) + 2;

        char * new_space = realloc(res, space_wanted * 1.5);
        if (new_space == NULL)
        {
          fprintf(stderr, "For some reason space was not able to be"
            " allocated.\n");
          return EXIT_FAILURE;
        }

        res = new_space;

        memcpy(res, orig, space_wanted);
        count++;
        res[count] = c;
        res[count + 1] = '\0';
      }
      else
      {
        return EXIT_SUCCESS;
      }

    }
  }
  return EXIT_SUCCESS;
}

最佳答案

realloc会将旧数据复制到新内存中,并释放旧内存(如果需要)。这意味着您不需要(也不应该)自己从旧内存中复制:

orig = res;
char* new_space = realloc(res, space_wanted * 1.5);
res = new_space;
memcpy(res, orig, space_wanted); // <-- undefined behavior, orig is potentially freed

关于c - 如何在while循环中使用realloc,使其适用于所有大小的空间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43852846/

10-13 07:21