getenv Returns different pointers every time it is called?
Sequel to my previous post here: http://www.linuxquestions.org/questi...u-8.04-662853/ I discovered a separate issue. I'm working with the same book, however now I'm trying to get the memory address of an environment variable. I googled around, and found this:
Quote:
What I have done is this: export MYVAR='test' echo $MYVAR And of course it echos 'test'. Here is the C source I'm trying to run (without the includes). Code:
int main(int argc, char *argv[]) { I added the second printf so that I can verify that the given address does actually contain the information, and it does every time. From what I've been reading, I gather that what I'm looking for is a thread safe version of getenv(), but I haven't found one thus far. I found this: https://www.securecoding.cert.org/co...ed+by+getenv() but either I don't understand it or it's not what I'm looking for. I'd appreciate if someone could give me a hand with this, I'm a little stuck. Thanks, -Peter |
How are you invoking the perl executable?
Some invocation functions allow you to pass a pointer to the environment space (execlp() is a good example). |
First off - environment variables (which argv[1] is not one of) are stored as part of the process memory - additions, ie., newly declared variables are inserted where there is free space. If there is no free space, then malloc is called to get more space. This means that the environment variables are stored in heap memory.
When you run a program it is the result of a fork()/exec() call. Meaning that you have a brand new process, with brand new variables, stored in memory in a new place. This means that every time you run a C program it can be loaded anywhere (almost) into memory, so the absolute addresses allocated in heap will be different. Secondly, if you want the address of "MYVAR" you have to call getenv("MYVAR"). The returned pointer is the address in the current process heap memory where the variable value is stored. Environment variables are stored as "SOMEVARIABLE=value". getenv returns the address of value, so you have to take what I said with a grain of salt - literally the part about addresses. And. C somewhat unwillingly supports Code:
int main(int argc, char ** rgv, char **envp) Code:
#include <stdlib.h> |
That's what I thought. Ok, so I abandoned all hope of finding the address and passing it via shell to the other program, and I wrote another program that uses getenv() to find the address and then use execle() to run my other binary so that the environment variable will still be there when it executes. It's not what the book says to do, but whatever, it works. Thanks for the help.
|
All times are GMT -5. The time now is 04:51 PM. |