where is the actual string of these two environment variable (a) environ b) envp) stored?

Viewed 257

I know at runtime, environ is a global pointer variable which ended up stored in the data section. envp is a local variable defined in the main, so it stores in the stack or top of the stack. Correct me if I am wrong.

But the question is, where is the actual string information these two environment stored? Both in the stack?

I attach the two code segments that these two environment variables are used. for environ:

#include <stdlib.h>
#include <stdio.h>
extern char **environ; 
int main(int argc, char **argv)
{ char **env_variable_ptr;
  env_variable_ptr = environ;
  while (*env_variable_ptr != NULL)
  { printf("%s\n", *env_variable_ptr);
    env_variable_ptr++;
  }
  printf("\n");
}

For envp:

int main(int argc, char **argv, char **envp){
    while(*envp != NULL){ 
    printf("%s\n", *envp);
    envp++;
    }
    printf("\n");
}
3 Answers

Check your specific compiler's documentation.

The language definition does not specify where they get stored, only how that storage should behave:

5.1.2.2.1 Program startup
...
2     If they are declared, the parameters to the main function shall obey the following constraints:
...
       —The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
C 2011 Online Draft

The standard does not define envp, but it's logical to assume any implementation that does would treat it the same as argv.

The argument vector, environment strings, and some extra information (the "auxiliary vector" on ELF-based systems) are usually placed above the bottom of the initial thread's stack. This location is used because the operating system has to create a read-write address range for the stack and write stuff to it, during process startup, anyway, so it may as well put all of the data that varies from invocation to invocation there.

This may be specified in the "processor-specific application binary interface" (psABI) document for your CPU and operating system. For instance, see the "process initialization" section of the x86-64/ELF psABI, used on most x86-64-based operating systems (with the prominent exception of Windows), particularly page 32 where it talks about the "information block."

On Linux, the data that forms the program's environment, along with the data that forms the program's arguments, is stored at the top of the program's address space, above the initial stack.

Pointers to the individual values -- both for environment and arguments -- are placed on the stack.

Because these locations are so close together (on Linux), you'll often see statements like "the environment data is placed on the stack". That's only partly true.

Related