[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Portability issue with `putenv'
From: |
Tim Van Holder |
Subject: |
Re: Portability issue with `putenv' |
Date: |
Tue, 22 Feb 2005 08:24:07 +0100 |
User-agent: |
Mozilla Thunderbird 1.0 (Windows/20041206) |
Sam Lauber wrote:
Ok, I give up! Any way to copy said string is very
welcome. If strcpy() does not do it's thing, what will?
1) strcpy() does do its thing but it needs valid memory
to copy the string to. Memory is typically allocated
using malloc() and its ilk.
So using
char* t = (char*) xmalloc(strlen(s) + 1);
strcpy(t, s);
would do the trick.
2) As mentioned by James, even with the adjusted code, you
introduce memory leaks for code that already malloc()s
the string it passes to putenv(), as it has no way of
free()ing the memory putenv() malloc()ed.
3) I'm not 100% sure, but I _think_ it is allowed to
modify the string you passed to putenv later, and that
such changes will have effect on future getenv() calls;
that behaviour is broken by your version of putenv().
Consider:
char myenvvar[1024];
snprintf(myenvvar, 1024, "%s=%s", "FOO", fooval1);
putenv(myenvvar);
/* getenv("FOO") returns fooval1 */
snprintf(myenvvar, 1024, "%s=%s", "FOO", fooval2);
/* getenv("FOO") returns fooval2 */
snprintf(myenvvar, 1024, "%s=%s", "BAR", "XYZZY");
/* getenv("FOO") returns NULL */
/* getenv("BAR") returns "XYZZY" */
This might not be allowed by POSIX though, and as such
may itself not be portable, in which case it doesn't
matter for the purpose of a portable putenv().