Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupThe {{getenv()}} function searches an environment list, provided by the host environment, for a string that matches a specified name. The {{getenv()}} function returns a pointer to a string associated with the matched list member. It is best not to store this pointer as it may be overwritten by a subsequent call to the {{getenv()}} function \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] or invalidated as a result of changes made to the environment list through calls to {{putenv()}}, {{setenv()}}, or other means. Storing the pointer for later use could result in a dangling pointer or a pointer to incorrect data.

Wiki Markup
According to C99 \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\]:

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.

This allows an implementation, for example, to copy the environmental variable to an internal static buffer and return a pointer to that buffer.

If you do not immediately use and discard this string, make a copy of the referenced string returned by getenv() so that this copy may be safely referenced at a later time. The getenv() function is not thread-safe. Make sure to address any possible race conditions resulting from the use of this function.

Implementation Details

According to the Microsoft Visual Studio 2005/.NET Framework 2.0 help pages:

...

Due to the way environment variables are stored, multiple environment variables with the same name can cause unexpected results.

Implementation Details

Depending on the implementation, a program may not consistently choose the same value if there are multiple environment variables with the same name. The GNU glibc library attempts to deal with this issue (in getenv() and setenv()) by always using the first variable it comes across, and ignoring the rest. unsetenv() will remove all the entries matching the variable name.

Non-Compliant Coding Example

...