How to handle unknow size user input in C
Here i shared two basic methods to handle user input in C.
1) scanf – this method is easy get attack by buffer overflow, try input some characters more than what you declare to experience buffer overflow
1 2 3 4 5 6 7 8 9 10 11 | #include <stdio.h> #include <stdlib.h> int main() { char bStr[80]; printf("\nEnter a very very very long String value:"); scanf("%s", bStr); printf("\nLong String value:%s \n\n",bStr); return 0; } |
2) fgets – this method can protect buffer overflow by limit the character user input
1 2 3 4 5 6 7 8 9 10 11 | #include <stdio.h> #include <stdlib.h> int main() { char bStr[80]; printf("\nEnter a very very very long String value:"); fgets ( bStr, 80, stdin ); printf("\nLong String value:%s \n\n",bStr); return 0; } |
However above two methods only can handle normal user input, how about i want to handle user input with 1000 or even more characters? Yes we can declare like “char bStr[1000]” or even more larger size, but this is not so dynamic and flexible enough. However we can use dynamic memory management in C to solve above problem, we can dynamic increase memory size with realloc() function.
First let see what above scanf() buffer overflow look like, just input more than what you declare and see the result below.
Buffer Overflow is not what we want. Here i share a dynamic memory allocation(realloc) in C to handle user input in unknown size.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <stdio.h> #include <stdlib.h> int main() { unsigned int len_max = 128; unsigned int current_size = 0; char *pStr = malloc(len_max); current_size = len_max; printf("\nEnter a very very very long String value:"); if(pStr != NULL) { int c = EOF; unsigned int i =0; //accept user input until hit enter or end of file while (( c = getchar() ) != '\n' && c != EOF) { pStr[i++]=(char)c; //if i reached maximize size then realloc size if(i == current_size) { current_size = i+len_max; pStr = realloc(pStr, current_size); } } pStr[i] = '\0'; printf("\nLong String value:%s \n\n",pStr); //free it free(pStr); pStr = NULL; } return 0; } |
Done, now this program can handle unknown size user input.









Very useful article.
welcome, actually i’m from java background, recently include in some C development project, hope my sharing is helpful
thanks… this is very informative,.. I am just starting c programming.