Problem with getenv() function.

i have been trying to fix it for days, still no luck.
i have searched web also.
here is my code
1
2
3
4
5
6
	char * a=getenv("APPDATA");
	strcat(a,"\\*.*");
	cout<<a<<endl;

	char * b=getenv("APPDATA");
	cout<<b<<endl;

in output i get string 'b' similar to 'a'.. why is this happening? even though i am storing the string from getenv() function to different char arrays..
Please help, i am completely stuck.
Regards
homi wrote:
even though i am storing the string from getenv() function to different char arrays.
.


You are incorrect.

When you use getenv - it returns a pointer to some static data.
That means that calling getenv repeatedly to get the same env data you
will receive the same pointer.
(so the pointers a and b in your code is pointing to
the same data in the environment data area)

You should NOT modify the text at the pointer because you are modifying the actual system data space ( and you certainly should not make the string longer like you
are doing).


refer to the microsoft documentation - or the documenation on this site.



Last edited on
It is NOT advisable to use this function in windows:

getenv operates only on the data structures accessible to the run-time library and not on the environment "segment" created for the process by the operating system. Therefore, programs that use the envp argument to main or wmain may retrieve invalid information.


http://msdn.microsoft.com/en-us/library/tehxacec%28v=vs.80%29.aspx

It is always recommended to use GetEnvironmentVariable() instead.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683188%28v=vs.85%29.aspx
http://pubs.opengroup.org/onlinepubs/007908799/xsh/getenv.html
The string pointed to must not be modified by the application, but may be overwritten by a subsequent call to getenv() or putenv()

The signature should be const char* getenv(void);
Last edited on
Thanks everyone for help..
if i use strings the problem is solved..

1
2
3
4
5
6
string env(string const& key)
{
    char const* val = getenv(key.c_str()); 
    return val == NULL ? string() : string(val);
}


@modoran: i am a little confused, do you mean getenv is not safe to use on windows?
its included in standard library, still unsafe?

Topic archived. No new replies allowed.