C语言 如何在 while 循环中使用 realloc,以便它适用于各种大小的空间



我在主函数中使用malloc和realloc来创建一个字符串,每当用户键入字符时,该字符串都会增加一个字节。但是,当字符串达到长度= 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] = '';
      }
      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

总结上面的所有输入,照顾讨厌的换行符并使代码更有效率,我想出了这段代码。

顺便说一句,count应该从 0 开始。

int main()
{
  int count = 0;
  int space_wanted;
  char * res;
  char c;

  res = malloc(1);
  *res = 0;   // or *res = '';
  printf("Instructions: type q to quit. Continually type characters to add"
     " it to the string.n");
  while ((c = fgetc(stdin)) != EOF && c != 'q' )
  {
     if ( c != 'n' )  //Disregard newline char
     {
        /* One space for the new character and also for the
           null character */
        space_wanted = strlen(res) + 2;
        if ( (res = realloc(res, space_wanted )) == NULL)
        {
            fprintf(stderr, "For some reason space was not able to be"
             " allocated.n");
            return -1;
        }
        res[count++] = c;
        res[count] = '';
    }
  }
  return 0;
}

相关内容

  • 没有找到相关文章

最新更新