...
Code Block |
---|
|
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++) {
if (puts(envp[i]);) == EOF) {
/* Handle Error */
}
}
}
return 0;
}
|
Because envp
no longer points to the current environment, this program has undefined behavior.
...
Code Block |
---|
|
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++) {
if (puts(environ[i]); == EOF) {
/* Handle Error */
}
}
}
return 0;
}
|
Non-Compliant Code Example (Windows)
...
Code Block |
---|
|
int main(int argc, char const *argv[], char const *envp[]) {
size_t i;
if (_putenv_s("MY_NEW_VAR", "new_value") != 0) {
/* Handle Error */
}
if (envp != NULL) {
for (i = 0; envp[i] != NULL; i++) {
if (puts(envp[i]); == EOF) {
/* Handle Error */
}
}
}
return 0;
}
|
Because envp
no longer points to the current environment, this program fails to print the value of MY_NEW_VAR
.
...
Code Block |
---|
|
_CRTIMP extern char **_environ;
/* ... */
int main(int argc, char const *argv[]) {
size_t i;
if (_putenv_s("MY_NEW_VAR", "new_value") != 0) {
/* Handle Error */
}
if (_environ != NULL) {
for (i = 0; _environ[i] != NULL; i++) {
if (puts(_environ[i]); == EOF) {
/* Handle Error */
}
}
}
return 0;
}
|
Compliant Solution
...