From 96b30ff94281a6f29e2159df3978b0524067f320 Mon Sep 17 00:00:00 2001 From: millert <> Date: Mon, 25 Apr 2016 21:36:04 +0000 Subject: [PATCH] Allow setenv(3) and putenv(3) to operate on a NULL environ pointer. The getenv(3) and unsetenv(3) functions already support this. This will make it easier to emulate the glibc clearenv() function in ports. Based on a diff from and OK jca@ --- src/lib/libc/stdlib/setenv.c | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/lib/libc/stdlib/setenv.c b/src/lib/libc/stdlib/setenv.c index 1182abda..60c2cd46 100644 --- a/src/lib/libc/stdlib/setenv.c +++ b/src/lib/libc/stdlib/setenv.c @@ -1,4 +1,4 @@ -/* $OpenBSD: setenv.c,v 1.17 2016/03/13 18:34:21 guenther Exp $ */ +/* $OpenBSD: setenv.c,v 1.18 2016/04/25 21:36:04 millert Exp $ */ /* * Copyright (c) 1987 Regents of the University of California. * All rights reserved. @@ -43,7 +43,7 @@ int putenv(char *str) { char **P, *cp; - size_t cnt; + size_t cnt = 0; int offset = 0; for (cp = str; *cp && *cp != '='; ++cp) @@ -65,13 +65,15 @@ putenv(char *str) } /* 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); - if (lastenv != environ) + if (lastenv != environ && environ != NULL) memcpy(P, environ, cnt * sizeof(char *)); lastenv = environ = P; environ[cnt] = str; @@ -122,15 +124,17 @@ setenv(const char *name, const char *value, int rewrite) 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); - if (lastenv != environ) + if (lastenv != environ && environ != NULL) memcpy(P, environ, cnt * sizeof(char *)); lastenv = environ = P; offset = cnt;