Versions Compared

Key

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

...

Code Block
bgColor#ffcccc
int main(int argc, char const *argv[], char const *envp[]) {
   size_t i;
   if (setenv("MY_NEW_VAR", "new_value", 1);) != 0) {
     /* Handle Error */
   }
   if (envp != NULL) {
      for (i = 0; envp[i] != NULL; i++) {
         puts(envp[i]);
      }
   }
   return 0;
}

...

Code Block
bgColor#ccccff
extern char **environ;

/* ... */

int main(int argc, char const *argv[]) {
   size_t i;
   if (setenv("MY_NEW_VAR", "new_value", 1); != 0) {
     /* Handle Error */
   }
   if (environ != NULL) {
      for (i = 0; environ[i] != NULL; i++) {
         puts(environ[i]);
      }
   }
   return 0;
}

Non-Compliant Code Example (Windows)

After a call to the Windows _putenv_s() function, or other function that modifies the environment, the envp pointer may no longer reference the environment.

Code Block
bgColor#ffcccc

int main(int argc, char const *argv[], char const *envp[]) {
   size_t i;
   if (_putenv_s("MY_NEW_VAR", "new_value", 1) != 0) {
     /* Handle Error */
   }
   if (envp != NULL) {
      for (i = 0; envp[i] != NULL; i++) {
         puts(envp[i]);
      }
   }
   return 0;
}

Because envp no longer points to the current environment, this program has undefined behavior.

Compliant Solution (Windows)

Use _environ in place of envp when defined.

Code Block
bgColor#ccccff
_CRTIMP extern char **_environ;

/* ... */

int main(int argc, char const *argv[]) {
   size_t i;
   if (_putenv_s("MY_NEW_VAR", "new_value", 1);) != 0) {
     /* Handle Error */
   }
   if (_environ != NULL) {
      for (i = 0; _environ[i] != NULL; i++) {
         puts(_environ[i]);
      }
   }
   return 0;
}

...

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section J.5.1, "Environment Arguments"
\[[MSDN|AA. C References#MSDN]\] [{{getenv, _wgetenv}}|http://msdn.microsoft.com/en-us/library/tehxacec.aspx], [{{_environ, _wenviron}}|http://msdn.microsoft.com/en-us/library/stxk41x1.aspx], [{{_putenv_s, _wputenv_s}}|http://msdn.microsoft.com/en-us/library/eyw7eyfw.aspx]
\[[Open Group 04|AA. C References#Open Group 04]\] [{{setenv()}}|http://www.opengroup.org/onlinepubs/009695399/functions/setenv.html]

...