Search code examples
cglibcgetenv

When getenv can alter content of previously returned pointer when using glibc?


C standard says that:

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.

As I understand, getenv implementation in glibc(I used ver. 2.17) returns element from global variable called char **environ. Every subsequent call to the getenv function still returns one of the elements from this array(or null when such env variable doesn't exist) without altering any of previously returned values.

Is any alternation of content of previously returned pointer by getenv function possible by subsequent call to the getenv function when using glibc? If yes, when?


Solution

  • This is really just a bug in the standards. Even C11 keeps language that allows the buffer to be overwritten, but at the same time, it does not permit data races with other calls to getenv, only with (implementation-defined) functions which modify the environment, so permitting this overwriting to take place seems contradictory.

    On all real-world implementations, including glibc, getenv returns the pointer to the copy of the string in the internal representation of the environment, and will never be invalidated except possibly if you call functions which modify the environment.