Why was putenv always broken?

Recently I found a bug in my replacement shell (“ash”) https://github.com/Elektraglide/ash where by if you set an environment variable (eg PATH=/bin) gradually all the env would get garbled.

I had been using putenv to change the variables and had vague memories from the 80s that it was ‘accepted wisdom’ that putenv was always broken - be it on AtariST, Sun workstations or whatever.

I broke out Ghidra and looked through the native shell program for Tek4404 and sure enough, it did its own thing and avoided putenv too.

Anyone remember this? Or am I halucinating like ChatGPT :slight_smile:

It’s a new one for me, but it seems the case that it was problematic, perhaps mainly because it’s easy to pass it a pointer to a local string, and that pointer may become invalidated later - putenv doesn’t copy the string.

From a CMU list of rules “SEI CERT C Coding Standard” for safe programming:

A potential error is to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.

The actual problem occurs when passing a pointer to an automatic variable to putenv(). An automatic pointer to a static buffer would work as intended.

See also

Also, seen in a usenet post “putenv() leaks memory” to comp.os.minix, a note about memory leaks:

As a side-effect, I’ve succesfully crashed a machine using the
following program:

void main(void)
{
while(1)
{
setenv("A","A",1);
setenv("A","AB",1);


}
}
2 Likes

Bingo! That’s the gotcha I had in mind from 40 years ago.

1 Like