0
0
CDebug / FixBeginner · 3 min read

How to Handle Errors in C: Simple Guide for Beginners

In C, errors are handled mainly by checking 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.

c
#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;
}
Output
Segmentation fault (or crash) because fopen failed and file is NULL
🔧

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.

c
#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;
}
Output
Error opening file: No such file or directory
🛡️

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 errno before calls, leading to misleading error messages.

Key Takeaways

Always check function return values to detect errors early.
Use errno and perror() to get clear system error messages.
Return error codes from your functions and handle them properly.
Avoid using pointers or resources without verifying they are valid.
Use tools to detect unchecked errors and improve code safety.