Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone give me example code of _dupenv_s?

Tags:

c++

visual-c++

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?

like image 232
user2264410 Avatar asked Apr 10 '13 04:04

user2264410


1 Answers

_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.

like image 171
Jonathan Potter Avatar answered Nov 15 '22 12:11

Jonathan Potter