News for hackers. Stuff that matters.
Re:C stdlib isn't threadsafe and even safe Rust didn't save us by kazinator on Thursday January 23, 2025 @07:31PM (#42809444)
The mutex would have to be held by the caller until it no longer needs the string returned from the environment, or makes a copy:

   stdenvlock();    // imaginary function added to ISO C or POSIX
   char *home = getenv("HOME");
   char *home_copy = strdup(home);
   stdenvunlock();  // only here can we unlock
   // home pointer is now indeterminate
Other solutions:

1. Put the above sequence into a function, and don't expose the mutex. Thread-safe code must use:

   char *home = dupenv("HOME"); // imaginary function; caller responsible for freeing.

2. Provide environment lookup into a buffer:

   getenvbuf("HOME", mybuf, sizeof mybuf);  // returns some value that helps to resize the buffer

   
All functions that retain pointers out of the classic getenv remain unsafe.

A mutex can be provided to those applications that want to manipulate the environ array directly, or use getenv and setenv, or any combinations of these.

The main problem is all the code out there using getenv.

There are no comments on this comment yet.