...
In a hosted environment, the main function receives a third argument,
char *envp[], that points to a null-terminated array of pointers tochar, each of which points to a string that provides information about the environment for this execution of the program.
Consequently, under a hosted environment it is possible to access the environment through a modified form of main():
...
After a call to the POSIX setenv() function, or another function that modifies the environment, the envp pointer may no longer reference the environment. POSIX states that [Open Group 2004]
unanticipated results may occur if
setenv()changes the external variableenviron. In particular, if the optionalenvpargument tomain()is present, it is not changed, and as a result may point to an obsolete copy of the environment (as may any other copy ofenviron).
...
Because envp may no longer point to the current environment, this program has undefined behavior.
Compliant Solution (POSIX)
...
According to the Visual C++ reference [MSDN],
The environment block passed to
mainandwmainis a "frozen" copy of the current environment. If you subsequently change the environment via a call toputenvor_wputenv, the current environment (as returned bygetenv/_wgetenvand the_environ/_wenvironvariable) will change, but the block pointed to byenvpwill not change.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
|
| ||||||
| PRQA QA·CQA-C |
| Fully implemented |
...
ISO/IEC 9899:2011 Section J.5.1, "Environment arguments"
Bibliography
[MSDN] getenv, _wgetenv, _environ, _wenviron, _putenv_s, _wputenv_s
[Open Group 2004] setenv()
...