Is scanf() function cause a buffer overflows? please explain this question by comparing the below code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is scanf() function cause a buffer overflows? please explain this question by comparing the below code?

https://code.sololearn.com/cDN29eVv2K9S/?ref=app Can this code cause a buffer flow? I raise this question because it access the users input without bothering about the input access limit

26th Jun 2020, 5:43 AM
Yogeshwaran
4 Answers
+ 1
For reading string; we can specify buffer size through the format specifier e.g. scanf("%5s", string_buffer); There we specify to read max up to 5 characters into <string_buffer>. The number used in the format specifier must be [buffer size - 1] because the last character must be reserved for string terminator. So allocate 6 characters for reading up to 5 characters, 11 for reading up to of 10 characters, and so on. http://www.cplusplus.com/reference/cstdio/scanf/
26th Jun 2020, 6:11 AM
Ipang
+ 1
Thanks Ipang In above code. I use char array { i.e char text[0] } To get string input and I also use scanf("%5s",text); to set limit for string input. But it works according to only scanf("%5s",text); It won't bother about the number(zero) present inside the char array index { i.e char text[0]; } Why, please anybody explain it?
26th Jun 2020, 8:05 AM
Yogeshwaran
+ 1
Yogeshwaran Once I read, that languages such as C or C++ allows you to "shoot yorself" in the foot (or anywhere you want, for that matter). I guess this is one of those cases :D
26th Jun 2020, 9:05 AM
Ipang
0
Ipang thanks for your guidance
26th Jun 2020, 3:15 PM
Yogeshwaran