Safe Reading Methods
char buffer[100];
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
}
Length Checking
int safeStringRead(char *buffer, int maxLength) {
if (fgets(buffer, maxLength, stdin) == NULL) {
return 0; // Read failed
}
// Trim newline
buffer[strcspn(buffer, "\n")] = 0;
// Additional length validation
if (strlen(buffer) >= maxLength - 1) {
// Handle overflow
return 0;
}
return 1;
}
Method |
Safety Level |
Pros |
Cons |
fgets() |
High |
Limits input length |
Includes newline character |
scanf() |
Medium |
Flexible |
Potential buffer overflow |
gets() |
Unsafe |
Deprecated |
No length checking |
graph TD
A[User Input] --> B[Length Check]
B --> C{Within Limit?}
C -->|Yes| D[Trim Newline]
C -->|No| E[Reject Input]
D --> F[Validate Content]
F --> G[Process Input]
Dynamic Memory Allocation
char* safeDynamicRead(int maxLength) {
char* buffer = malloc(maxLength * sizeof(char));
if (buffer == NULL) {
return NULL; // Memory allocation failed
}
if (fgets(buffer, maxLength, stdin) == NULL) {
free(buffer);
return NULL;
}
// Remove newline
buffer[strcspn(buffer, "\n")] = 0;
return buffer;
}
LabEx Security Recommendations
- Always set maximum input length
- Use fgets() instead of gets()
- Remove trailing newline
- Validate input content
- Handle potential errors
Error Handling Example
int processUserInput() {
char buffer[100];
if (!safeStringRead(buffer, sizeof(buffer))) {
fprintf(stderr, "Input error or too long\n");
return 0;
}
// Additional input validation
if (strlen(buffer) < 3) {
fprintf(stderr, "Input too short\n");
return 0;
}
// Process valid input
printf("Valid input: %s\n", buffer);
return 1;
}
Key Takeaways
- Always limit input length
- Use fgets() for safe reading
- Implement thorough input validation
- Handle potential error scenarios
- Never trust user input unconditionally