c++environment-variablesc++builder-xe8

Using getenv() to read environment variable returns NULL C++


I am attempting to read an environment variable in C++ as per this documentation. My code looks like this:

char * val;
val = getenv( "smartDir" );

ShowMessage( val );

delete val;

My problem is that val always ends up NULL as if the enviroment variable does not exist. However, I clearly have the variable defined as you can see here:

enter image description here

What am I doing wrong here?


Solution

    1. you should not delete pointer returned by getenv (see here, part about undefined behavior)
    2. if you're changing global environment, please keep in mind, that env. is assigned to process at its start and all child processes inherit it from parent. So if you start program from IDE/console started before env change it will not be reflected in its child process.

    To make testing easier: most IDEs provide 'Environment' setting under 'Debugging' settings - you can change there env passed to child process (your program) (Visual has it, QtCreator has it, C++Builder probably has it also etc.)

    If you execute your program from console: use SET var=value instead of changing global env, to make local change before passing env to child process.

    Both solutions do not modify global env and allow to quickly test different env settings.