A combination of calloc() (which you are already using) and realloc() would be used to dynamically size your buffers to accommodate various lengths of user input.
However, there are several issues in your existing example code that should be addressed before going on to use that combination: See suggestions and comments below:
As written, your existing code will leak memory as you never call free().
Also, you will get a buffer overrun in string
. (see explanation below)
Here ere are a couple of corrections that will allow your example code to work: (see comments)
#define LGTH_STRING_INPUT 20
//have written function to accept argument, easier to free memory
char* readStringInp(char *string){
//char* string=NULL,c=NULL;//done in main
int c; //getchar() requires int to detect EOF (-1)
int i=0;
//string=malloc(LGTH_STRING_INPUT); //do not cast return value of calloc
// max length allow should be LGTH_STRING_INPUT - 1
// to allow room for NULL after loop
for(i=0;i<LGTH_STRING_INPUT-1 && ( (c=getchar()) != '\n' && c != EOF );i++)
{
string[i]=c;
}
string[i]='\0';
return string;
}
int main(void)
{
char *buf = {0};
char bufIn[LGTH_STRING_INPUT];
//allocated and free memory in calling function:
buf = malloc(LGTH_STRING_INPUT);
if(buf)//check return of malloc
{
sprintf(bufIn, "%s", readStringInp(buf)); //use return value in buffer
free (buf);//free memory that has been created
}
return 0;
}