如何在while循环中使用realloc,以便它适用于所有大小的空间?

时间:2017-05-08 16:34:35

标签: c malloc realloc

我在main函数中使用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] = '\0';
      }
      else
      {
        return EXIT_SUCCESS;
      }

    }
  }
  return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

BTW,count应该从0开始。

int main()
{

  int count = 0;
  int space_wanted;
  char * res;
  char c;


  res = malloc(1);
  *res = 0;   // or *res = '\0';

  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] = '\0';

    }
  }
  return 0;
}