c - 在不知道要输入的字符串大小的情况下动态分配内存

标签 c pointers realloc fgetc getc

下面的函数返回一个指向字符串的字符指针,该字符串是使用 getc(stdin) 逐个字符初始化的。

  1. 内存分配方法是否有缺陷?当我们不知道要输入的字符串的大小时,这是一种有效的方法吗?如果不是,请解释一下。

  2. 使用getc(stdin)——会导致缓冲区溢出吗???()

  3. 如果我不能使用 getc(stdin),什么可以帮助我以更有效的方式实现我的目标?

到目前为止的代码:

char *getstring()
{
  char *str = NULL, *tmp = NULL;
  int size = 0, index = 0;
  int ch = -1;
  int length=0;
  while (ch!=0) 
  {
    ch = getc(stdin);

    if (ch == '\n')
    {   
        ch = 0;
    }

    if (size <= index) 
    {
        size += 15;
        tmp = (char*)realloc(str, size);
        if (!tmp) 
        {
            free(str);
            str = NULL;    
        }
        str = tmp;
    }
    str[index++] = ch;
  }

  if(size==index)
  {
    return str;
  }
  else if(index<size)
  {
    length=strlen(str);
    tmp = (char*)realloc(str,(length+1));
    str[index]='\0';
    //cout<<"length:"<<length;
    str=tmp;
  }

  return str;
}

最佳答案

不要重新发明轮子:使用getline(3) .

示例(来自同一 URL):

   #define _GNU_SOURCE
   #include <stdio.h>
   #include <stdlib.h>

   int
   main(void)
   {
       FILE *stream;
       char *line = NULL;
       size_t len = 0;
       ssize_t read;

       stream = fopen("/etc/motd", "r");
       if (stream == NULL)
           exit(EXIT_FAILURE);

       while ((read = getline(&line, &len, stream)) != -1) {
           printf("Retrieved line of length %zu :\n", read);
           printf("%s", line);
       }

       free(line);
       fclose(stream);
       exit(EXIT_SUCCESS);
   }

关于c - 在不知道要输入的字符串大小的情况下动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463141/

相关文章:

c - 重新分配(再次)

c - realloc 如何增加内存块的大小?

c - 打印 EOF 的值

使用 c 程序更改应用程序核心转储目录

c - 双方都有副作用吗?

c - 从 C 中的指针实例化一个新结构

c - 通过 GTK 或 GDK 直接在屏幕上绘图

c - 如何在结构中保存任意数量字符的数组

c++ - 为什么从constexpr引用生成的汇编代码与constexpr指针生成的汇编代码不同?

c - 在 realloc 之后组织指针数组