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

后端 未结 9 1440
臣服心动
臣服心动 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:15

    I think that you should replace all the function-calls if possible to call an implementation of your own. A good example here would be a function to replace strcpy and call the compiler-specific version of strcpy inside it. Your implementation can then easily be modified to suit any compiler of your choice, specifically if you will be adding or changing platforms/compilers.

    Example:

    
    char* StringCopy(char* Destination, const char* Source, size_t DestinationSize)
    {
    #ifdef _MSC_VER
      return strcpy_s(Destination, Source, DestinationSize);
    #else
      if(!(strlen(Source) >= DestinationSize))
         return strcpy(Destination, Source);
      else
         return 0x0;
    #endif
    }
    
    0 讨论(0)
  • 2020-12-05 11:16

    You don't really need pragmas to disable them.

    For win32/msvc, in ProjectProperties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions, add following macros:

    _CRT_SECURE_NO_DEPRECATE  
    _CRT_NONSTDC_NO_DEPRECATE
    

    Or you can pass thos in command line parameters (-D_CRT_SECURE_NO_DEPRECATE). You can probably #define them at the beginning of certain *.cpp files. Also, there are probably more of them (see crtdefs.h - looks like there are a lot of them...). Those kind of warnings normally tell you with which macros you can disable them - just read compiler output.

    0 讨论(0)
  • 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); 
    
    0 讨论(0)
提交回复
热议问题