4

I am exploring a simple ELF binary with gdb on my machine right now. If I see correctly, all environment variables are loaded into the stack of the process.

I am assuming that they are provided to user applications in case they are needed by the developer or some libc function (e.g. execve).

However, is it not a little bit of an overhead and memory waste for the operating system to copy all of them in every process' memory space, if only a couple of applications really need them? Is there maybe another reason I did not think of?

Alexander Grass
  • 384
  • 2
  • 11

1 Answers1

2

That the vars are placed on the stack is an implementation detail. They could have been stored someplace else; e.g., attached to the kernel structure that defines the properties of each process. They are put on the stack because that means the info can be paged out (e.g., to swap space) if the system gets low on memory.

Regardless of where the info is stored the UNIX process model requires that each process have a private copy of its env vars. This is why, for example, you can't modify the env vars of any process other than the current process.

The memory overhead is one reason you should minimize the number env vars. I've seen people define over a thousand env vars which is, frankly, absurd and an abuse of the env var mechanism. The 47 env vars defined in my interactive shells require 2050 bytes of memory; which is almost exactly 1/2 of a 4 KiB page of memory. It is an inconsequential amount of memory.

Kurtis Rader
  • 6,734
  • 13
  • 20