0

Hi I'm working with C++ on Linux platform, i have to get the value of a environment variable(user defined) and use it further. Following is the code I'm using,

const char *show_line = getenv ("MY_SHOW_LINES");

bool myFlag = (strcmp(show_line, "1") == 0) ? false : true;

Above code executes properly when i set the value of environment variable(MY_SHOW_LINES) equal to 1 but when i unset the value of it(i.e. unset MY_SHOW_LINES). Above code gives memory fault. Any suggestion on above UN-expected behavior?? Thanks in advance

BSalunke
  • 11,499
  • 8
  • 34
  • 68

2 Answers2

4

If you pass a NULL pointer to strcmp, you get undefined behavior, in this case a very likely crash.

Are you aware that pointers can be NULL, i.e. purposely invalid?

You should guard against this possibility:

bool myFlag = false; // set default value
if ( show_line != NULL ) {
    myFlag = ( strcmp(show_line, "1") != 0 ); // "? false : true" same as NOT…
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

According to the man page,

The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

So if it doesn't exist, it returns NULL, which causes digestion problems for strcmp().

glglgl
  • 89,107
  • 13
  • 149
  • 217