C ErrorsLesson 48Free preview
C Input Validation
This lesson is part of C · All levels
Summary
Input validation ensures that the input data is in line with the program's expectations from the type, range, and format side before further processing. User inputs are a source of bugs and security gaps such as buffer overflow, so any input should be considered unreliable and limited in length. If the input is invalid, the program should reject it with a clear message or request re-entry.
Key points
- Check the scanf results, the number of items that you read, before using the input value.
- Limit the width of the field such as scanf("%19s", buf) so that the buffer does not overlap.
- Validation ranges, for example, should be between 1 and 100, and formats such as numbers or letters.
- For the full text, use fgets with a buffer size limit and make sure the end of the string contains the null terminator.
- Treat all input sources as unreliable: users, files, and networks.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.