Skip to content
systemcoding.dev
Systems Programming

Save errno immediately after a failing call

Save errno into a local variable right after a failing call, before any printf or free can overwrite it, in C on POSIX systems.

2 min read
Summarize in AI

errno is one shared variable that any library call may change, even a successful one. Code that checks the failure first and prints later can show the wrong message. The tip is to copy the value on the line after the call, as errno(3) warns: its value is set by failing calls and may be altered by a successful one, so it should be read right after the call.

saveerrno.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int open_config(const char *path) {
    int fd = open(path, O_RDONLY);
    if (fd < 0) {
        int saved = errno;
        fprintf(stderr, "opening %s\n", path);   /* may reset errno */
        errno = saved;
        return -1;
    }
    return fd;
}

int main(void) {
    if (open_config("/nonexistent") < 0)
        printf("failed: %s\n", strerror(errno));
    return 0;
}
Text
opening /nonexistent
failed: No such file or directory

Cleanup calls such as close, free and fclose can overwrite errno when they run before the error is reported. In a function that undoes work on the failure path, save the value first and put it back before returning, as the code does, so the caller still sees the original cause. A signal handler that calls library functions should save and restore it too. Never assume errno is zero after success: set it to 0 yourself before calls such as strtol that report errors only through it.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.