The strings used by the environment variables in the current process state are not necessarily in contiguous memory. Some environment variables may have been removed by the startup code, or changed or added by a call to putenv
or setenv
. These changes are not necessarily reflected in the array of strings that envz_get
examines because they are performed by changing the pointers (not the strings) in the environment array.
Here's an example that demonstrates this:
#include <assert.h>
#include <envz.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main (int argc, char **argv, char **envp)
{
assert (envp[0] != NULL);
assert (envp[1] != NULL);
char *first_name = strndup (envp[0], strcspn (envp[0], "="));
char *second_name = strndup (envp[1], strcspn (envp[1], "="));
printf ("removing: %s\n", second_name);
unsetenv (second_name);
printf ("getenv (%s): %s\n", first_name, getenv (first_name));
size_t size = 0;
for (size_t i = 0; envp[i] != NULL; ++i)
size += strlen (envp[i]) + 1;
printf ("envz_get (%s): %s\n",
first_name, envz_get (envp[0], size, first_name));
printf ("getenv (%s): %s\n",
second_name, getenv (second_name));
printf ("envz_get (%s): %s\n",
second_name, envz_get (envp[0], size, second_name));
}
On my system, it prints this:
removing: LESSCLOSE
getenv (STY): 9173.pts-0.deneb
envz_get (STY): 9173.pts-0.deneb
getenv (LESSCLOSE): (null)
envz_get (LESSCLOSE): /usr/bin/lesspipe %s %s