views:

321

answers:

3

I write a C program gets in an environment variable's name and print out it's memory address, simply use the getenv() function to do the job. Let's say I wanna have the address location of PATH --> ./test PATH. But when I debug that program in gdb, the memory location of that variable is different. Can you explain in detail why is there such a different?

To be more exact:

./test PATH --> 0xbffffd96

debug in gdb --> 0xbffffd53

[edit] Thanks for your explanations. What I actually in question about is, how the memory address of a variable (in this case, an environment variable) changes with different programs. For example, I have 2 program a.out and b.out

./a.out --> PATH's address is some number

./b.out --> another number

So, what causes this difference between 2 numbers? I hope I have clearly demonstrated what I want to ask. Thanks mates.

+1  A: 

Why would you expect it to return the same memory location every time? getenv returns "a pointer to a string containing the value for the specified name." It is not specified which memory location the string is located at, nor whether that location will later be overwritten.

Matthew Flaschen
Sorry for my ambiguous example. In my program there should be something like this: printf("%p",getenv("PATH")) for example
Your question wasn't ambiguous. I understood you were asking about the memory address ("%p"). However, as others say, you should not care about this.
Matthew Flaschen
+2  A: 

Typically, environment variables are part of some "process data block", and those are inherited from the starting process. If you are running a program in a debugger, that debugger will have its own process data block and your program will inherit its process data block from the debugger. That in turn might have inherited the program data block of the IDE.

This doesn't matter anyway, because the interface to the environment variables doesn't give you that kind of details. For instance, on Windows it's quite likely that the environment variables will be converted from Unicode to your local 8 bit codepage when you ask for them. You'd never see the original variable, just (an approximation of) its value.

MSalters
+3  A: 

Perhaps you want to do?

printf("%s",getenv("PATH"));


Getting the environment variable string does make sense.
But, the address where the system gives you the string, has no relevance anywhere
(particularly outside the scope of this program).

You should be interested in the environment string value rather than its address.
If you have any reason to use the address, please give that here.

For example,

echo $PATH

gives me,

/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin: ... etc

All my programmatic interest with PATH would be in its contents not any sort of address.

nik
Edited in a missing parenthesis.
Magnus Skog