It is already safe to call getenv() and unsetenv() when environ is
NULL so I think it makes sense for setenv() and putenv() to also
support this. However, I'd prefer that we just wrap the loop that
counts the length of environ in an if (environ != NULL) check rather
than needlessly check for NULL in each iteration of the loop. This
also makes it more obvious that the check is for a NULL environ.
- todd
--- /usr/src/lib/libc/stdlib/setenv.c Mon Apr 25 14:15:14 2016
+++ setenv.c Mon Apr 25 14:27:32 2016
@@ -43,7 +76,7 @@
putenv(char *str)
{
char **P, *cp;
- size_t cnt;
+ size_t cnt = 0;
int offset = 0;
for (cp = str; *cp && *cp != '='; ++cp)
@@ -65,9 +98,11 @@
}
/* create new slot for string */
- for (P = environ; *P != NULL; P++)
- ;
- cnt = P - environ;
+ if (environ != NULL) {
+ for (P = environ; *P != NULL; P++)
+ ;
+ cnt = P - environ;
+ }
P = reallocarray(lastenv, cnt + 2, sizeof(char *));
if (!P)
return (-1);
@@ -122,11 +156,13 @@
break;
}
} else { /* create new slot */
- size_t cnt;
+ size_t cnt = 0;
- for (P = environ; *P != NULL; P++)
- ;
- cnt = P - environ;
+ if (environ != NULL) {
+ for (P = environ; *P != NULL; P++)
+ ;
+ cnt = P - environ;
+ }
P = reallocarray(lastenv, cnt + 2, sizeof(char *));
if (!P)
return (-1);