CERT-ENV31-C
In this section:
Synopsis
Do not rely on an environment pointer following an operation that may invalidate it
Enabled by default
Yes
Severity/Certainty
Low/Medium

Full description
Modifying the environment by any means may cause the environment memory to be reallocated, invalidating the `envp' pointer
Coding standards
- CERT ENV31-C
Do not rely on an environment pointer following an operation that may invalidate it
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[], const char *envp[]) {
if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
/* Handle error */
}
if (envp != NULL) {
for (size_t i = 0; envp[i] != NULL; ++i) {
puts(envp[i]);
}
}
return 0;
}
The following code example passes the check and will not give a warning about this issue:
#include <stdio.h>
#include <stdlib.h>
extern char **environ;
int main(void) {
if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
/* Handle error */
}
if (environ != NULL) {
for (size_t i = 0; environ[i] != NULL; ++i) {
puts(environ[i]);
}
}
return 0;
}