visual-c++compiler-warningscrtgetenvc-standard-library

"getenv... function ... may be unsafe" - really?


I'm using MSVC to compile some C code which uses standard-library functions, such as getenv(), sprintf and others, with /W3 set for warnings. I'm told by MSVC that:

'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

Questions:


Solution

  • getenv() is potentially unsafe in that subsequent calls to that same function may invalidate earlier returned pointers. As a result, usage such as

    char *a = getenv("A");
    char *b = getenv("B");
    /* do stuff with both a and b */
    

    may break, because there's no guarantee a is still usable at that point.

    getenv_s() - available in the C standard library since C11 - avoids this by immediately copying the value into a caller-supplied buffer, where the caller has full control over the buffer's lifetime. dupenv_s() avoids this by making the caller responsible for managing the lifetime of the allocated buffer.

    However, the signature for getenv_s is somewhat controvertial, and the function may even be removed from the C standard at some point... see this report.