Safe Way to Handle User Input in C

Are you new in C? Many tutorial in the world wide talk about C. Why I want to share this? Because, if you not handle input properly especially in C, your program will broken. Why this happen? You never know when someone will break your program within the hole from user input. Some principal I quote for this things from OWASP, check here.

Don’t Trust User Input.

In C when you not limited the user input and the user input larger than the container, the input filled up your container and also fill another container. It is also called Buffer Overflow. The key for handle the user input, limited the user input same with you define the container for that input. I tell how limited the user input used standard input in C. (You should pay attention too when used C standard library in C++).

Photo by Ariel on Unsplash

Using scanf()

Are scanf() always safe to use handle user input? I think the answer is yes when you properly define the format correctly. See the different from code below.

Without Limited Long of The Input
Limited Long of Input

We can see the different is the format input in scanf(). When you bring input string with larger than 5 character (try 20 character or more) that will break your program in first code. Second code still take 5 character to save into str1. Another standard input you used should be limited the input will store to variable or container. I bring some example too.

Use fgets() besides gets()

See this example when using gets().

Using gets

When you try string with character more than 5, It also break your program. You should try another function like fgets that take input with some value. Look this example.

Using fgets

Are you see the different? You limited the user input. This type of input will keep away from Buffer Overflow. You can check another function that handle the user input too. You should check the length of buffer or input from user. Also when you copy, concat, sometimes print too should be check the buffer size. You should use strncpy() besides strcpy(). You should use strncat() besides strcat().

Summary

You should limited the user input as you limited the container or variable too. Use the input function correctly and handle the user input carefully. I recommend to always predict the length of user input should be and what maximum space from container you can save it. I hope with this article, you will aware with your code from now. Have a great day!

Backend Developer — Focus at Microservices and Cloud Computing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store