[Techtalk] environ variable in C

Akkana Peck akkana at shallowsky.com
Fri Apr 2 19:26:31 EST 2004


David Sumbler writes:
> I'm carrying on with my attempts to learn C.
> 
> I've just been experimenting with a little program to print out the
> contents of the "environ" variable.
> 
> For some reason it doesn't print all of my bash environment variables
> - it prints rather less than half of them.

Are you sure those are all environment variables?  They're all
exported, they're not just bash shell variables?  Does the printenv
command print more variables than your C program?

> BTW, I'm sure there's nothing wrong with the program, which is
> straight out of Beginning Linux Programming:
> 
> #include <stdlib.h>
> #include <stdio.h>
> 
> extern char **environ;

I've always used envp, as the third argument to main --
int main(int argc, char** argv, char** envp)
or else used getenv("SPECIFIC_VAR_NAME").
If printenv prints out more variables than your program is showing,
try envp and see if it's any different.

>    while(*env) {

In a real program, it might be worth doing while (env && *env) just
in case environ ever becomes null.  Probably shouldn't happen, but
being safe doesn't cost much.

	...Akkana


More information about the Techtalk mailing list