Warning C4996: This function or variable may be unsafe — compared to GCC on POSIX

前端 未结 3 1428
无人共我
无人共我 2020-12-30 01:08

I notice that MS compilers give \"deprecated\" warnings for cstdlib functions like getenv. MS has invented its own standard such as _dupenv_s

相关标签:
3条回答
  • 2020-12-30 01:38

    It annoys the heck outta me that Microsoft chose to do this. I know how to call all the functions safely, I don't want or need these extra warnings.

    Just set _CRT_SECURE_NO_WARNINGS and be done with it. It's really that silly.

    0 讨论(0)
  • 2020-12-30 01:41

    For the specific case of getenv, it is indeed not reentrant or thread safe. As for why Microsoft doesn't just replace it, you can't take that interface and make it reentrant (you can almost make it "thread safe" with thread local storage, but it would still not be reentrant).

    Even if you just took getenv away altogether, there is still the problem that you have the environ variable which would require some serious compiler level support to make thread safe, since it is just data.

    Really, using environment variables for anything other than "setting it up before the process starts or at process start, and only reading from it from that point on" is going to probably end in tears if you have more than one thread. setenv and putenv don't have a rich enough interface to express something like "set this set of environment variables atomically" and likewise getenv doesn't have a way to express "read this set of environment variables atomically".

    _dupenv_s is somewhat silly in my opinion, because if using that suddenly makes your code safe, it could probably done in a safe way with getenv. _dupenv_s solves a tiny subset of the problems with using environment variables in a multithreaded scenario.

    0 讨论(0)
  • 2020-12-30 01:42
    1. In a sane world, the answer would be "of course not, that would be stupid!" In this world, though, it seems there is no end of gut-wrenchingly poorly thought out undocumented behavior upon which people will stoop to depending upon. Raymond Chen has a great collection of such anecdotes (anecdon'ts?) in his blog. Such as the hideous practice of using a bug in the loader to share thread-local variables between an exe and a DLL. When you have as many customers as Microsoft does, the only safe choice is to never even risk breaking backwards compatibility.

    2. The difference in warnings is because cl.exe is going out of its way to highlight a potential security problem, and g++ isn't. getenv and puts and friends are all still broken under POSIX, but (at least for getenv) there isn't a more secure alternative in the standard library. And, unlike Microsoft, the GNU folks probably see a standard library call with potential security problems as a lesser evil than a more secure but platform-specific library call.

    0 讨论(0)
提交回复
热议问题