cgetenv

Mysterious getenv() seg faults


I am trying to export variable and read it back using getenv() but for some reason, it gives me a segmentation fault..

#include<stdio.h>
#include<stdlib.h>

int main(){
    system("export LINES=$(stty size | awk '{print $1}');"
        "export COLUMNS=$(stty size | awk '{print $2}')");
    printf("%s %s\n", getenv("LINES"), getenv("COLUMNS"));
    return 0;
}

I'm running Ubuntu 14.04.

The weird thing is that it runs normally on gdb, and the compiler output shows no error while compiling, even with -Wall -Wextra...
Why is this happening?


Solution

  • The child process run by system() doesn't affect the environment of the process that calls system().

    Therefore, the shell executed by system() doesn't set LINES or COLUMNS in the environment of the calling process, so getenv() is probably returning a pair of null pointers, which is somehow causing grief… Except that printf() often works correctly even when a null pointer is passed to it for formatting with %s (it produced (null) for me, but that is not behaviour mandated by the C standard).

    If you want to set an environment variable, you should use setenv(). You may come across old code that uses putenv() instead, but you should not use that in new code.