BurntSushi/ripgrep · error

could not find NUL terminator in hostname

Error message

could not find NUL terminator in hostname

What it means

After a successful libc::gethostname call, POSIX permits the returned buffer to lack a NUL terminator when the hostname was truncated to fit the buffer. This code scans the buffer for the first 0 byte; if none exists it refuses to guess and returns this error. It guards against returning garbage bytes as the hostname.

Source

Thrown at crates/cli/src/hostname.rs:70

        return Err(io::Error::new(io::ErrorKind::Other, msg));
    };
    // maxlen here includes the NUL terminator.
    let mut buf = vec![0; maxlen];
    // SAFETY: The pointer we give is valid as it is derived directly from a
    // Vec. Similarly, `maxlen` is the length of our Vec, and is thus valid
    // to write to.
    let rc = unsafe {
        libc::gethostname(buf.as_mut_ptr().cast::<libc::c_char>(), maxlen)
    };
    if rc == -1 {
        return Err(io::Error::last_os_error());
    }
    // POSIX says that if the hostname is bigger than `maxlen`, then it may
    // write a truncate name back that is not necessarily NUL terminated (wtf,
    // lol). So if we can't find a NUL terminator, then just give up.
    let Some(zeropos) = buf.iter().position(|&b| b == 0) else {
        let msg = "could not find NUL terminator in hostname";
        return Err(io::Error::new(io::ErrorKind::Other, msg));
    };
    buf.truncate(zeropos);
    buf.shrink_to_fit();
    Ok(OsString::from_vec(buf))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn print_hostname() {
        println!("{:?}", hostname().unwrap());
    }
}

View on GitHub (pinned to 3fce3b5bb0)

Solutions

  1. Shorten the system hostname so it fits within _SC_HOST_NAME_MAX and is NUL-terminated.
  2. Restart the process/kernel so sysconf and the actual hostname agree.
  3. Fall back to reading the hostname from /etc/hostname or an env var instead of calling hostname().
Defensive patterns

Strategy: fallback

Try / catch

let host = match grep_cli::hostname() {
    Ok(n) => n,
    Err(_) => std::env::var("HOSTNAME").map(Into::into).unwrap_or_default(),
};

Prevention

When it happens

Trigger: The system's real hostname is longer than the value reported by _SC_HOST_NAME_MAX, gethostname writes a full buffer with no terminator, and buf.iter().position(|&b| b == 0) returns None.

Common situations: A hostname that was lengthened after sysconf was queried, a container with an unusually long FQDN exceeding the kernel's max, or a libc/POSIX-compliance quirk. Extremely rare in practice.

Related errors


AI-assisted analysis of BurntSushi/ripgrep@3fce3b5bb0 (2026-08-06). Data as JSON: /data/errors/c74b8de145647e5e.json. Report an issue: GitHub.