下面的函数返回一个指向字符串的字符指针,该字符串是使用 getc(stdin)
逐个字符初始化的。
内存分配方法是否有缺陷?当我们不知道要输入的字符串的大小时,这是一种有效的方法吗?如果不是,请解释一下。
使用
getc(stdin)
——会导致缓冲区溢出吗???()如果我不能使用
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/