Input validation is crucial for preventing unexpected program behavior and potential security vulnerabilities. It ensures that user input meets specific criteria before processing.
Basic Validation Techniques
Type Checking
#include <stdio.h>
#include <stdlib.h>
int validate_integer_input(char *input) {
char *endptr;
long value = strtol(input, &endptr, 10);
if (*endptr != '\0' && *endptr != '\n') {
return 0; // Invalid input
}
return 1; // Valid input
}
int main() {
char input[100];
printf("Enter an integer: ");
fgets(input, sizeof(input), stdin);
if (validate_integer_input(input)) {
int number = atoi(input);
printf("Valid input: %d\n", number);
} else {
printf("Invalid input\n");
}
return 0;
}
Range Validation
int validate_range(int value, int min, int max) {
return (value >= min && value <= max);
}
int main() {
int age;
printf("Enter your age (0-120): ");
scanf("%d", &age);
if (validate_range(age, 0, 120)) {
printf("Valid age\n");
} else {
printf("Invalid age\n");
}
return 0;
}
Advanced Validation Strategies
graph TD
A[Input Received] --> B{Type Check}
B --> |Valid| C{Range Check}
B --> |Invalid| D[Reject Input]
C --> |Valid| E[Process Input]
C --> |Invalid| D
Validation Method Comparison
Validation Type |
Complexity |
Use Case |
Type Checking |
Low |
Ensuring correct data type |
Range Validation |
Medium |
Limiting input to specific bounds |
Regex Validation |
High |
Complex pattern matching |
Removing Whitespace
void trim_input(char *str) {
int start = 0, end = strlen(str) - 1;
while (str[start] && isspace(str[start])) start++;
while (end > start && isspace(str[end])) end--;
str[end + 1] = '\0';
memmove(str, str + start, end - start + 2);
}
Preventing Buffer Overflow
#define MAX_INPUT 100
int safe_input(char *buffer, int max_length) {
if (fgets(buffer, max_length, stdin) == NULL) {
return 0; // Input error
}
// Remove newline if present
buffer[strcspn(buffer, "\n")] = 0;
return 1;
}
Best Practices
- Always validate user input
- Use appropriate validation methods
- Provide clear error messages
- Implement multiple validation layers
At LabEx, we emphasize the importance of robust input validation to create secure and reliable C programs.