A co-worker just asked me if it was safe to use getenv() in static initializers, that is, before main(). I looked in Stevens, and in the Posix Programmer's Guide, and the best I can find is
An array of strings called the enviroment is made available when the process begins. This array is pointed to by the external variable
environ, which is defined as:
extern char **environ;
It's that environ variable that has me hesitating. I want to say
-The calling process/shell has already allocated the block of null terminated strings
-the 'external' variable environ is used as the entry point by getenv().
-ipso facto feel free to call getenv() within a static initializer.
But I can't find any guarantee that the 'static initialization' of environ precedes all the other static initialization code. Am I overthinking this?
Update
On my platform (AMD Opteron, Redhat 4, GCC 3.2.3), setting LD_DEBUG shows that environ gets set before my static initializers are called. This is a nice thing to know; thanks, @codelogic. But it is not necessarily the result I'd get on all platforms.
Also, while I agree intuitively with @ChrisW on the behavior of the C/C++ runtime library, this is just my intuition based on experience. So anyone who can pipe up with a quote from someplace authoritative guaranteeing that environ is there before static initializers are called, bonus points!