Date: 2010apr28
Language: C/C++
Q. C/C++: Why isn't my putenv() working?
A. You probably need to make a duplicate like this:
putenv(strdup(s));
if you are passing a local variable to putenv()
This fixes the immediate problem but the duplicate string is never freed.
However, its better to use setenv() like this:
setenv("MYVAR", "thevalue", true);
Since it makes a copy and is clearer.
Full Example Use:
#include <stdio.h>
#include <stdlib.h>
// We set from a local (stack) variable to show a copy is made
void set1() {
auto val1 = "one";
setenv("MYVAR", val1, true);
}
void set2() {
auto val2 = "two";
setenv("MYVAR", val2, true);
}
int main() {
set1();
printf("value1=%s\n", getenv("MYVAR"));
set2();
printf("value2=%s\n", getenv("MYVAR"));
}
Output:
value1=one
value2=two
As you can see, the environment variable is updated.