scanf() is lousy!!

Rahul GoyalRahul Goyal
2 min read

Issue โŒ

scanf() is a very lousy function ๐Ÿ˜ช due to which it can cause many runtime errors and even security issues๐Ÿ“ข in our code that are very very difficult to catch.๐Ÿ˜จ A scanf looks like:

scanf("%s", food);

Now here, when a user enters input, he can use as much memory and this can lead to over flow because memory allocated to food variable is limited. We can put a limit like "%8s" and then we can only input 8 characters but still, this is not a mandatory condition and can lead to rise in errors if a developer just forgets to put it because compiler will now not complain to use the limit, it will work as it is and now is vulnerable to memory leaks... โ—โ—

Can software not be stricter

Now here comes our savior which is fgets(). This function will mandatorily ask you for the size of input and hence we cannot just forget to put a limit. ๐Ÿ˜„๐Ÿ˜„ It looks something like this:

fgets(food, sizeof(food), stdin);

Here stdin tells that fgets() would read input from standard input. Also size of input is passed as an argument.๐Ÿ’ฏ๐Ÿ’ฏ

โš  Warning โš 

If we are passing in an array variable then its fine to use sizeof, but if in case of pointer decay i.e. a pointer variable is passed to fgets() for an array then size limit would be equal to size of pointer and not the size of array. This can lead to issues and wrong input size limit in fgets(). To safeguard from this we should pass size of array manually or just pass a variable containing size in second argument rather than using sizeof() ๐Ÿ’š๐Ÿ’š

If its useless, then why scanf() ?? ๐Ÿค”

Now, here comes the limitation of fgets() that it can only input in one variable and that to a string, not any other type, but scanf() can be used to take multiple inputs of specified data types.

Conclusion

Use fgets() if we want to enter a simple unstructured string data and use scanf() when we want to input structured data with many fields. ๐Ÿ˜Žโค

I Hope you now understand when to use what input and why I say scanf() is lousy. ๐Ÿ˜ช

0
Subscribe to my newsletter

Read articles from Rahul Goyal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul Goyal
Rahul Goyal