scanf() is lousy!!

scanf() is a lousy function. Lets see what can we do then πŸ€”

Β·

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. πŸ˜ͺ

Β