What Is errno and How Does It Work in C
errno is a per-thread integer that C library and system calls set on failure. Learn when it is valid and how to read it correctly with glibc 2.41.

When a system call fails in C, it tells you in two places at once. The return value says that something went wrong, usually by being -1, and a variable called errno says what went wrong. This post explains what errno is, when you are allowed to read it, and the three mistakes that account for most of the confusing bugs beginners meet. It uses C11 and POSIX.1-2024 on Linux with glibc 2.41. The definition comes from the POSIX specification of errno.h, and the broader subject is the hub of this cluster, the complete guide to error handling in systems code.
What errno is
errno is an integer variable declared in <errno.h>. When a library function or a system call fails, it stores a positive error number in it, such as ENOENT (2, "No such file or directory") or EACCES (13, "Permission denied"). The names are macros for small positive integers, and the exact numbers are defined by the platform, so you should always compare against the names and never the digits.
Here is the smallest program that shows the pattern. It opens a file that does not exist and prints the error number.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
int fd = open("/no/such/file", O_RDONLY);
if (fd == -1)
printf("open failed, errno = %d\n", errno);
return 0;
}On Linux, the output is:
open failed, errno = 2The number 2 is ENOENT. The function reports failure through the return value, and errno supplies the reason. That split is the first thing to learn: **the return value tells you whether the call failed, and errno tells you why**.
errno is only meaningful after a failure
The most common beginner mistake is to read errno without checking the return value. A successful call is allowed to leave errno at any value, including a leftover from an earlier failure. The standard says that no library function sets errno to zero, and that a function may change it even when it succeeds. So this code is wrong:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p = getenv("HOME");
if (errno != 0) /* wrong: errno was never reset */
perror("getenv");
printf("HOME=%s\n", p ? p : "(unset)");
return 0;
}If something earlier in the process, perhaps inside the C runtime start-up, had set errno to a non-zero value, this prints a spurious error even though getenv succeeded. The correct rule is: check the return value first, then read errno only in the failure branch.
A small number of functions have no distinguished failure value, and for them the documented method is to set errno = 0 before the call and test it afterward. strtol is the classic example, because it returns LONG_MAX on overflow but LONG_MAX is also a legitimate result.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
errno = 0;
long v = strtol("99999999999999999999", NULL, 10);
if (errno == ERANGE)
printf("out of range, clamped to %ld\n", v);
else
printf("value %ld\n", v);
return 0;
}On a 64-bit Linux system, where long holds up to 9223372036854775807, the output is:
out of range, clamped to 9223372036854775807Setting errno = 0 first is the only way to tell an overflow from an input that really was LONG_MAX.
How errors map to values
A table helps. The same variable is used by two very different groups of functions, and the failure signal differs.
| Function family | Failure signal | Where errno is valid |
|---|---|---|
System call wrappers such as open, read, write, close | return -1 | after a -1 return |
Pointer-returning calls such as malloc, fopen | return NULL | after a NULL return |
strtol, strtod | no unique failure value | only if you cleared it before the call |
pthread_* functions | return the error number directly | errno is not used |
The last row surprises people. The POSIX threads functions, for example pthread_mutex_lock, return 0 on success and a positive error number on failure, and they do not touch errno. Reading errno after a failed pthread_create gives you stale data. Use the return value itself as the error code.
Turning a number into a message
Numbers are for programs, and messages are for people. The standard library provides strerror, which maps an error number to a string, and perror, which prints your prefix, a colon, a space and that string to standard error. The next post in this cluster covers both in detail. For now, this is enough:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
if (open("/no/such/file", O_RDONLY) == -1)
fprintf(stderr, "open: %s (errno %d)\n", strerror(errno), errno);
return 1;
}open: No such file or directory (errno 2)Two things that overwrite errno
errno is one variable, and anything that fails can change it. If you call another function between the failure and your use of errno, the value you read may belong to that second function. The usual culprit is a call that you made to clean up or report the error.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int fd = open("/no/such/file", O_RDONLY);
if (fd == -1) {
close(fd); /* fails with EBADF: errno overwritten */
printf("errno = %d\n", errno);
}
return 0;
}errno = 9Number 9 is EBADF, from the close(-1) call, and the real cause, ENOENT, is gone. The fix is to save errno in a local variable right after the failing call and use the copy. This matters even more in signal handlers and in logging code, and a later post in this cluster, on preserving errno across cleanup, covers it in depth.
Where the variable lives
On modern systems errno is not a plain global. In glibc it is a macro that expands to a function-call-like expression returning an lvalue in thread-local storage, so each thread has its own copy. That design is what makes errno safe in multi-threaded programs, and a separate post in this cluster explains why it exists. For a beginner the consequence is simple: one thread's failed system call does not change another thread's errno, and you never need to lock around it. You must still not declare it yourself with extern int errno;, because that is wrong on any system where it is a macro. Always include <errno.h>.
A worked example that gets it right
Putting the rules together, here is a small function that reads a whole file into memory and reports every failure with the right reason. It checks the return value of each call, saves errno before doing cleanup, and restores it so the caller sees the original cause.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Returns a malloc'd buffer and sets *len, or NULL with errno set. */
char *slurp(const char *path, size_t *len)
{
int fd = open(path, O_RDONLY);
if (fd == -1)
return NULL; /* errno already set by open */
size_t cap = 4096, used = 0;
char *buf = malloc(cap);
if (!buf) {
int saved = errno;
close(fd);
errno = saved;
return NULL;
}
for (;;) {
if (used == cap) {
cap *= 2;
char *bigger = realloc(buf, cap);
if (!bigger) {
int saved = errno;
free(buf);
close(fd);
errno = saved;
return NULL;
}
buf = bigger;
}
ssize_t n = read(fd, buf + used, cap - used);
if (n == -1) {
int saved = errno;
free(buf);
close(fd);
errno = saved;
return NULL;
}
if (n == 0)
break;
used += (size_t)n;
}
close(fd);
*len = used;
return buf;
}
int main(void)
{
size_t n;
char *data = slurp("/no/such/file", &n);
if (!data) {
perror("slurp");
return 1;
}
free(data);
return 0;
}slurp: No such file or directoryThe pattern repeats on every failure path: copy errno into saved, run the cleanup, assign it back. It looks fussy, but it is the price of the single shared variable. A caller of slurp can now trust errno the way it trusts it after open, which means the function follows the same convention as the system calls it wraps. A later post in this cluster shows how goto can collapse those repeated cleanup blocks into one.
Reading the list of possible errors
Each function documents the values it may set. The man page section called ERRORS lists them, and the POSIX page for open does the same in the standard's own words. Read it before you write the failure branch, because the list tells you which failures are worth handling specially. For open, ENOENT means the path does not exist, EACCES means permission was refused, EMFILE means your process has too many files open, and EINTR can appear if a signal arrived. Each suggests a different reaction: create the file, report a permission problem, close something, or retry. Treating all of them as one generic failure throws that information away.


