Below is the function which returns a character pointer to a string which was initialized using getc(stdin)- character by character.
Is there any flaw in memory allocation method? Is this an efficient way when we don't know the size of the string which is going to be entered, if not please explain.
Using
getc(stdin)--will it lead to buffer overflow???()If I must not use
getc(stdin), what will help me achieve my goal in a more efficient way?
Code so far:
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;
}
ch?stris NULL ifreallocfails,str[index++] = ch;=>NULL[index++] = ch;