C4996 (function unsafe) warning for strcpy but not for memcpy

前端 未结 7 2236
青春惊慌失措
青春惊慌失措 2020-11-27 08:03

I am writing code in VS2010 and I happen to see after compilation compiler gives me C4996 warning (\"This function or variable may be unsafe\") for strcpy and sprintf calls.

相关标签:
7条回答
  • 2020-11-27 09:01

    The reason why you get a warning on sprintf and strcpy, and not on memcpy, is because memcpy has a length parameter that limits how much memory you copy. For strcpy and memcpy, the input has to be terminated with a \0. If not, it will continue out of bounds. You can limit this by using the snprintf and strncpy functions. Those do limit implicitly how much can be copied.

    Note that microsoft has deprecated snprintf, so you should use the replacement function _snprintf instead. However, this is a MSVC specific function.

    I would advise to do away with char * buffers all together and switch to C++, using stl container, such as std::string. These will save you a lot of debugging headaches and keep your code portable.

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