0
0
CHow-ToBeginner · 3 min read

How to Use strerror in C: Simple Error Message Handling

In C, strerror converts an error number (like errno) into a readable string describing the error. You pass the error code to strerror, and it returns a pointer to a message you can print or log.
📐

Syntax

The strerror function has this syntax:

  • char *strerror(int errnum);

Here, errnum is the error number you want to describe, usually from the global errno variable. The function returns a pointer to a string describing the error.

c
char *strerror(int errnum);
💻

Example

This example shows how to use strerror to print a readable error message when a file open operation fails.

c
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main() {
    FILE *file = fopen("nonexistent.txt", "r");
    if (!file) {
        printf("Error opening file: %s\n", strerror(errno));
        return 1;
    }
    fclose(file);
    return 0;
}
Output
Error opening file: No such file or directory
⚠️

Common Pitfalls

One common mistake is to assume strerror returns a new string you can modify or free. It returns a pointer to a static string that should not be changed or freed.

Also, errno must be checked immediately after a failing function call because it can be overwritten by other calls.

c
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main() {
    FILE *file = fopen("missing.txt", "r");
    if (!file) {
        const char *msg = strerror(errno); // Correct: do not modify msg
        printf("Error: %s\n", msg);
    }
    return 0;
}
Output
Error: No such file or directory
📊

Quick Reference

Tips for using strerror:

  • Use errno to get the last error code after a failed system call.
  • Pass errno to strerror to get a readable message.
  • Do not modify or free the string returned by strerror.
  • Check errno immediately after the error to avoid overwriting.

Key Takeaways

Use strerror(errno) to get a readable error message from the last error code.
Do not modify or free the string returned by strerror; it points to static memory.
Check errno immediately after a failing function call to get the correct error.
strerror helps make error handling messages clear and user-friendly.