Menu

Your Rust Code Sets an Environment Variable and the 2024 Edition Calls That Unsafe
📰

Your Rust Code Sets an Environment Variable and the 2024 Edition Calls That Unsafe

DEV Community: rust·Serguey Asael Shinder·18 days ago
#QgP2HE7H
#devtorust#devto#dev#unsafe#edition
Long article (326 words) — no AI summary yet.
Reading 0:00
15s threshold

The service had one line

at the top of main:

std::env::set_var("TZ", "UTC");

Harmless for years.

Then the team

moved the crate

to the 2024 edition.

It stopped compiling.

The compiler said

set_var is an unsafe function

and needs an unsafe block.

One environment variable.

Unsafe.

Here is the mechanism.

On Linux and most Unix systems,

the environment is a plain C array

owned by the C library.

setenv can move it,

or free old entries,

while it changes it.

getenv reads it

with no lock that Rust controls.

Rust's own std::env functions

take a lock.

C code does not.

And C code

reads the environment

all the time.

Time zone lookups.

DNS resolution.

Locale setup.

Any C library

your crate links.

So one thread sets a variable

while another resolves a hostname,

and the reader can follow a pointer

into memory that was just freed.

A crash.

Or wrong data.

Or nothing,

for months,

and then a crash

nobody can reproduce.

Rust's promise

is that safe code

cannot cause that.

set_var…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.