Can anyone give me example code of _dupenv_s?

c++, visual-c++

Solution

`_dupenv_s` is a Microsoft function, designed as a more secure form of `getenv`.

`_dupenv_s` allocates the buffer itself; you have to pass it a pointer to a pointer and it sets this to the address of the newly allocated buffer.

For example,

char* buf = nullptr;
size_t sz = 0;
if (_dupenv_s(&buf, &sz, "EnvVarName") == 0 && buf != nullptr)
{
    printf("EnvVarName = %s\n", buf);
    free(buf);
}

Note that you're responsible for freeing the returned buffer.

Problem

I'm using `getenv("TEMP")`, but I'm getting a warning telling me to use `_dupenv_s`. I can't find an example of _dupenv_s on the net. The docs read: ``` errno_t _dupenv_s( char **buffer, size_t *numberOfElements, const char *varname ); ``` But what buffer are they referring to? I only have varname. Wouldn't it be better to avoid using a buffer?

Original source