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.
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.
#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;
}opening /nonexistent
failed: No such file or directoryCleanup 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.