【发布时间】:2012-08-22 14:44:57
【问题描述】:
不久前我在这个网站上看到了一个功能,我把它做了一些调整以供我使用。
它是一个使用 getc 和 stdin 检索字符串并精确分配包含该字符串所需的内存的函数。然后它只返回一个指向已分配内存的指针,该内存填充了所述字符串。
我的问题是这个函数有什么缺点(除了以后必须手动释放分配的内存)吗?你会做些什么来改进它?
char *getstr(void)
{
char *str = NULL, *tmp = NULL;
int ch = -1, sz = 0, pt = 0;
while(ch)
{
ch = getc(stdin);
if (ch == EOF || ch == 0x0A || ch == 0x0D) ch = 0;
if (sz <= pt)
{
sz++;
tmp = realloc(str, sz * sizeof(char));
if(!tmp) return NULL;
str = tmp;
}
str[pt++] = ch;
}
return str;
}
在使用您的建议后,这里是我更新的代码,我决定只使用 256 字节作为缓冲区,因为此函数用于用户输入。
char *getstr(void)
{
char *str, *tmp = NULL;
int ch = -1, bff = 256, pt = 0;
str = malloc(bff);
if(!str)
{
printf(\nError! Memory allocation failed!");
return 0x00;
}
while(ch)
{
ch = getc(stdin);
if (ch == EOF || ch == '\n' || ch == '\r') ch = 0;
if (bff <= pt)
{
bff += 256;
tmp = realloc(str, bff);
if(!tmp)
{
free(str);
printf("\nError! Memory allocation failed!");
return 0x00;
}
str = tmp;
}
str[pt++] = ch;
}
tmp = realloc(str, pt);
if(!tmp)
{
free(str);
printf("\nError! Memory allocation failed!");
return 0x00;
}
str = tmp;
return str;
}
【问题讨论】:
-
是的!这正是我第一次看到这个函数的地方。
-
您的修订版更加明智。您可能还想考虑为每个 realloc() 将
bff乘以 2,请参阅 Qnan 和我在他的回答 cmets 中的讨论。尽管如此,如果您说这只是用于手动用户输入,那么您所拥有的一切都很好。
标签: c string dynamic input stdin