cglibcgetenv

Do envz_get and getenv reference the same pool of environment variables?


Do getenv() and envz_get() both look up environment variables from the same source if the latter is passed the optional envp argument to int main (int argc, char *argv[], char *envp[])?

In other words, does the optional envp argument to int main (int argc, char *argv[], char *envp[]) refer to the same pool of environment variables that is referenced by getenv()?


Solution

  • In my experience, yes, they are identical. It doesn't seem like getenv() would be particularly useful if they weren't. This isn't something I'd tested in decades, but in response to your question, I just ran a test, and while getenv() is allowed by the standard to use a static memory area for its returns, its return values all pointed to the first character after the equal sign in the third argument to main. It's my vague recollection this happened the last time I did this test, too, though that was a different unix system.

    That having been said, looking at the standard, or as close as I can reasonably come to that... From the last free proposed C17 draft:

    The getenv function searches an environment list, provided by the host environment, for a string that matches the string pointed to by name . The set of environment names and the method for altering the environment list are implementation-defined. The getenv function need not avoid data races with other threads of execution that modify the environment list. 305)

    The implementation shall behave as if no library function calls the getenv function. Returns The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function. If the specified name cannot be found, a null pointer is returned.

    305) Many implementations provide non-standard functions that modify the environment list.

    Which basically means, probably, but the C language doesn't exactly guarantee it.