Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is char *envp[] as a third argument to main() portable

In order to get an environment variable in a C program, one could use the following:

  • getenv()
  • extern char **environ;

But other than the above mentioned, is using char *envp[] as a third argument to main() to get the environment variables considered part of the standard?

#include <stdio.h>  int main(int argc, char *argv[], char *envp[]) {     while(*envp)         printf("%s\n",*envp++); } 

Is char *envp[] portable?

like image 481
Sangeeth Saravanaraj Avatar asked Apr 25 '12 18:04

Sangeeth Saravanaraj


People also ask

What is the third argument in Main?

The third parameter, envp, is an array of pointers to environment variables. The envp array is terminated by a null pointer. See The main Function and Program Execution for more information about main and envp.

What is an environment variable in C?

Standard environment variables are used for information about the user's home directory, terminal type, current locale, and so on; you can define additional variables for other purposes. The set of all environment variables that have values is collectively known as the environment.


2 Answers

The function getenv is the only one specified by the C standard. The function putenv, and the extern environ are POSIX-specific.

EDIT

The main parameter envp is not specified by POSIX but is widely supported.

An alternative method of accessing the environment list is to declare a third argument to the main() function:

int main(int argc, char *argv[], char *envp[]) 

This argument can then be treated in the same way as environ, with the difference that its scope is local to main(). Although this feature is widely implemented on UNIX systems, its use should be avoided since, in addition to the scope limitation, it is not specified in SUSv3.

like image 188
cnicutar Avatar answered Sep 24 '22 15:09

cnicutar


It isn't portable. *envp[] is a traditional UNIX thing, and not all modern UNIX systems implement it.

Also as a side note you could access envp by doing a pointer traversal over *argv[], overflowing it...but i don't think that can be considered safe programming. If you take a look at the process memory map you will see that envp[] is just above argv[].

like image 40
skyel Avatar answered Sep 21 '22 15:09

skyel