0

When we do setenv() or putenv(), the book 'Advanced Programming in the UNIX Environment' says that when we modifying value of environment lists, it's complicated.

Basically, environment lists are stored at the top of stack.

However, the book says, in name=value structure, if we change the old value of a name to a new value, which is larger than old value, we must malloc() to obtain room for the new string, copy the new string to this area, and then replace the old pointer in the environment list for corresponding name with the pointer to this allocated area (it must be heap area, because we use malloc()).

But, basically environment lists are stored at the top of the stack. So, new value has to be located at here, not heap area (area of malloc()). So, why this value is at heap area, not top of the stack?

There is the char** environ global variable, and this double pointer points array of pointers which points at name=value strings. I thought this name=value strings are one of the data which is pointed by environ's array of pointer. This is why I can't understand that array of pointer points heap area (which stores new value in above situation).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
A.Cho
  • 571
  • 1
  • 6
  • 17

1 Answers1

2

Once you start modifying the environment, there's no requirement that the new information be placed at the top of the stack. In fact, there's no requirement that the original environment be placed at the top of the stack, but that's a common location for it. The only requirement is that environ points to a null-terminated array of char * values, each of which is the value of an environment variable (order is not specified), so that getenv() knows where to search, and putenv(), setenv() and unsetenv() know what to operate on. If you use putenv(), then it is basically guaranteed that the new environment variable (or new value for existing environment variable) won't be in the same area as the original. There's nothing to stop you hardwiring an environment variable value in a static string that is allocated in the (read-only) text segment, or in a static array. If you use setenv(), the new value might be in amongst the original, but is more likely to be elsewhere.

See also Questions about putenv() and setenv().

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278