How to get rid of “unsafe” warnings / errors in Visual Studio (strcpy, sprintf, strdup)

后端 未结 9 1510
臣服心动
臣服心动 2020-12-05 10:43

I\'m trying to get rid of some compiler warnings that say strcpy, sprintf, etc are unsafe. I get why they\'re unsafe, but I can\'t think of a good way to fix the code, in a

9条回答
  •  情歌与酒
    2020-12-05 11:20

    If getting rid of warnings only is your objective... simply define this _CRT_SECURE_NO_WARNINGS and it will suppress all the deprecation warnings. But this will not fix the underlying problems with unsafe CRT functions.

    If you are on visual studio version >= 2005 and want to fix these warnings in a proper way... easiest method is to #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 and #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 1 in your project.

    without any further code changes you can observe most of the warnings are fixed automatically. By defining this windows will automatically call the secure overloaded functions for most of the unsafe CRT functions. Buffer sizes for static arrays are calculated automatically.

    Although Dynamically allocated buffers are not fixed by this way and we need to fix them manually. Please refer this link for further details.

    Below is a way to correct your example programatically

    strcpy_s(extList->names[i], length, extName); 
    

提交回复
热议问题