How to Handle Errors in C: Simple Guide for Beginners
return values from functions and using the global errno variable for system errors. You can also use perror() to print readable error messages based on errno.Why This Happens
Errors in C happen because many functions return special values to indicate failure, but if you ignore these values, your program may behave incorrectly or crash. Also, system calls set a global variable errno to explain what went wrong, but if you don't check it, you miss the error details.
#include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("nonexistent.txt", "r"); // Not checking if file is NULL char buffer[100]; fgets(buffer, 100, file); // This causes undefined behavior printf("Read: %s\n", buffer); fclose(file); return 0; }
The Fix
Always check the return value of functions like fopen(). If it returns NULL, handle the error gracefully. Use perror() to print a clear error message based on errno.
#include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("nonexistent.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; // Exit or handle error } char buffer[100]; if (fgets(buffer, 100, file) != NULL) { printf("Read: %s\n", buffer); } fclose(file); return 0; }
Prevention
To avoid errors, always check function return values before using their results. Use errno and perror() for system-related errors. Adopt a consistent error handling style, such as returning error codes from your functions and documenting them. Use static analysis tools or linters to catch unchecked return values.
Related Errors
Common related errors include:
- Using pointers without checking for
NULL. - Ignoring return values from memory allocation functions like
malloc(). - Not resetting
errnobefore calls, leading to misleading error messages.
Key Takeaways
errno and perror() to get clear system error messages.