Set environment variables in C

Viewed 79335

Is there a way to set environment variables in Linux using C?

I tried setenv() and putenv(), but they don't seem to be working for me.

5 Answers

Not an answer to this question, just wanna say that putenv is dangerous, use setenv instead.

putenv(char *string) is dangerous for the reason all it does is simply append the address of your key-value pair string to the environ array. Therefore, if we subsequently modify the bytes pointed to by string, the change will affect the process environment.

#include <stdlib.h>

int main(void) {
    char new_env[] = "A=A";
    putenv(new_env);

    // modifying your `new_env` also modifies the environment
    // vairable
    new_env[0] = 'B';
    return EXIT_SUCCESS;
}

Since environ only stores the address of our string argument, string has to be static to prevent the dangling pointer.

#include <stdlib.h>

void foo();

int main(void) {
    foo();
    return EXIT_SUCCESS;
}

void foo() {
    char new_env[] = "A=B";
    putenv(new_env);
}

When the stack frame for foo function is deallocated, the bytes of new_env are gone, and the address stored in environ becomes a dangling pointer.

Related