The C standard says getenv()
has the following behavior [ISO/IEC 9899:2011]:
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 thegetenv
function.
Consequently, it is best not to store this pointer, as it may be overwritten by a subsequent call to the getenv()
function 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 can result in a dangling pointer or a pointer to incorrect data. This string should be referenced immediately and discarded; if later use is anticipated, the string should be copied so the copy can be safely referenced as needed.
...
CERT C++ Secure Coding Standard: ENV00-CPP. Do not store the pointer to the string returned by getenv()
ISO/IEC 9899:2011 Section Section 7.22.4, "Communication with the environment," and Section 7.22.4.6, "The getenv
function"
ISO/IEC TR 17961 (Draft) Using an object overwritten by getenv, localeconv, setlocale, and strerror [libuse]
...
[MSDN] _dupenv_s()
and _wdupenv_s()
, getenv_s()
, _wgetenv_s()
[Open Group 2004] Chapter 8 , and "Environment Variables," strdup
[Viega 2003] Section 3.6, "Using Environment Variables Securelyenvironment variables securely"
...