3

I am using MS Visual Studio 2008 for developing a C++ application. I use the 'getenv()' function to fetch an environment variable, but when the searched environment variable doesn't exist, it throws an access violation exception. What is the issue here and how to correct it?

The docs say that the getenv() function will return a NULL pointer if the searched environment variable doesn't exist, but why am I getting this access violation exception?

Guruprasad
  • 1,447
  • 4
  • 16
  • 34
  • Likely you're not checking if getenv() returns NULL. Show us code. – Erik Mar 08 '11 at 11:59
  • What are you doing witht he return value from getenv? It sounds like your are dereferencing the returned NULL. For example, trying to put it into a string like `std::string var = getenv ("MY_VAR")` will do it. – Pete Mar 08 '11 at 12:00

1 Answers1

5

The std::string class calls strlen when you use std::string(str), which will produce an access violation when passed a NULL string. What you need to do is something like:

std::string env(const char *name)
{
    const char *ret = getenv(name);
    if (!ret) return std::string();
    return std::string(ret);
}

or

bool getenv(const char *name, std::string &env)
{
    const char *ret = getenv(name);
    if (ret) env = std::string(ret);
    return !!ret;
}

which you could use like this:

std::string myenv;
if (getenv("MYENV", myenv))
    doSomethingWithMyEnv(myenv);
reece
  • 7,945
  • 1
  • 26
  • 28