c++pointersgetenv

C++ getenv() wrapper function not setting the value


The cplusplus.com documentation on getenv() states...

The pointer returned points to an internal memory block, whose content or validity may be altered by further calls to getenv

...which I take to mean, "If you want to keep the content, copy it." So, since I need to retrieve several variables, I wrote a couple of little wrapper functions:

#include <iostream>
#include <string.h>

using namespace std;

void getEnv (char *val, const char *var) {
    val = nullptr;
    char *enVar = getenv(var);
    if (enVar != nullptr) {
        val = new char[strlen(enVar) + 1];
        strcpy(val, enVar);
    }
}

void getEnv (int &val,  const char *var) {
    val = -1;
    char *enVar = getenv(var);
    if (enVar != nullptr) {
        val = atoi(enVar);
    }
}

int main() {
    char *textMode = nullptr;
    int  cLen = 0;

    getEnv(cLen, "CONTENT_LENGTH");
    cout << cLen << endl << endl;

    getEnv(textMode, "TEXT_MODE");
    if (textMode == nullptr)
        cout << "Not set.";
    else 
        cout << "[" << textMode << "]<br>\n";

    return 0;
}

The int version works as expected, but I get nothing back from the char version, and I mean nothing: if I don't initialize *textMode at declaration it remains an uninitialized pointer.

It's pointers, right? Right? I know it is. Gotta be pointers. I'll figure them out one of these days, but hey -- at least I got my linked list to work! Yay!


Solution

  • Your second function takes val (an int) by reference: void getEnv (int &val, const char *var) and so can modify the variable passed to it as you expect.

    Your first function takes val (a char*) by value: void getEnv (char *val, const char *var) so modifying val has no affect on the variable passed to it. A simple solution is to simply take it as a reference as well: void getEnv (char *&val, const char *var)