Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Question 1

AFAIK the main "unsafe" thing is about reentrancy *. Since MS's CRT is marked as "multi-threaded" (/MT), why don't they just replace getenv with the reentrant, thread-safe version? Is it like anybody would depend on the unsafe behavior?

Question 2

I compiled the same code with GCC g++ -Wall -Wextra -Weff++ -pedantic foo.cpp and it doesn't yield any warnings. So I guess this is not a problem on POSIX? How is this solved? (OK maybe they just changed the behavior of getenv, would be nice to have this confirmed).

* It's an over-generalization to say that its' only about reentrancy. Of course we have things like strncpy_s which changes the signature completely and deals with buffer size. But doesn't change the core of this question

like image 956
kizzx2 Avatar asked Nov 26 '10 16:11

kizzx2


People also ask

Why is Getenv unsafe?

getenv suffers like much of the classic C Standard Library by not bounding the string buffer length. This is where security bugs like buffer overrun often originate from. If you look at getenv_s you'll see it provides an explicit bound on the length of the returned string.


2 Answers

  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.

like image 170
Ben Karel Avatar answered Oct 01 '22 15:10

Ben Karel


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.

like image 24
Joshua Avatar answered Oct 01 '22 13:10

Joshua