errno is assigned a nonzero literal

ID

c.maintainability.errno_assigned_nonzero

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Numeric Operation

Language

C / C++

Description

Reports a direct assignment of a nonzero numeric literal to errno, such as errno = 5; or errno = -1;. Assigning 0 is the one value application code is permitted to store in errno directly.

Rationale

errno is a modifiable lvalue reserved for the C library and the operating system to report the cause of a failed call; application code is only meant to read it after a call fails, and to reset it to 0 before a call whose success is checked through errno alone. Storing a made-up nonzero value manufactures a failure code the underlying platform never produced, which misleads any later strerror(errno) or errno-based branch into reporting or acting on a condition that never happened.

The following code illustrates the pattern detected by this rule:

void call_something(void)
{
    // FLAGGED: errno is assigned a nonzero literal
    errno = 5;

    // FLAGGED: errno is assigned a nonzero literal
    errno = -1;

    errno = 0;

    errno = 0x0;

    int saved = errno;

    errno = saved;

    errno = EINVAL;
}

Remediation

Do not assign application-defined error codes to errno. Reset it with errno = 0; before a call, and after the call let the library set errno itself; report an application-level error through the function’s own return value or a dedicated status type instead.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved