environment: fix up memory accesses when building envp

This commit is contained in:
Ariadne Conill 2020-07-23 09:43:09 -06:00
parent a2f3169716
commit 2c556d8655

View file

@ -28,21 +28,23 @@ lif_environment_push(char **env[], const char *name, const char *val)
/* create an initial envp: {"foo=bar", NULL} */ /* create an initial envp: {"foo=bar", NULL} */
if (*env == NULL) if (*env == NULL)
{ {
*env = calloc(1, sizeof (**env)); *env = calloc(2, sizeof (char *));
**env = strdup(buf); (*env)[0] = strdup(buf);
(*env)[1] = NULL;
return true; return true;
} }
size_t nelems; size_t nelems;
for (nelems = 0; *env[nelems] != NULL; nelems++) for (nelems = 0; (*env)[nelems] != NULL; nelems++)
; ;
nelems += 1; /* NULL at end, plus next env var */
*env = realloc(*env, (nelems * sizeof (**env))); size_t allocelems = nelems + 2;
*env = realloc(*env, ((allocelems + 2) * sizeof (char *)));
*env[nelems] = strdup(buf); (*env)[nelems] = strdup(buf);
*env[nelems + 1] = NULL; (*env)[nelems + 1] = NULL;
return true; return true;
} }
@ -52,6 +54,8 @@ lif_environment_free(char **env[])
{ {
size_t nelems; size_t nelems;
for (nelems = 0; *env[nelems] != NULL; nelems++) for (nelems = 0; (*env)[nelems] != NULL; nelems++)
free(*env[nelems]); free((*env)[nelems]);
free(*env);
} }