Crt secure no warnings ошибка

I have a compile error in my simple MFC window application generated from wizard with several lines of code:

error C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

I set Configuration Properties>>C/C++>>Preprocessor>>Preprocessor Definitions>> _CRT_NONSTDC_NO_WARNINGS

But this doesn’t help. I have another very close project that generates only warning in this place and it has no _CRT_NONSTDC_NO_WARNINGS definition.

The only difference between the projects is several different options in wizard.

Why does _CRT_NONSTDC_NO_WARNINGS not help in the first project and why does the second project compile without problems without this definition?

AJM's user avatar

AJM

1,2772 gold badges15 silver badges30 bronze badges

asked Mar 17, 2014 at 9:15

vico's user avatar

6

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor
Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

Sumurai8's user avatar

Sumurai8

20.2k11 gold badges65 silver badges99 bronze badges

answered Mar 17, 2014 at 9:37

Balu's user avatar

BaluBalu

2,2071 gold badge17 silver badges23 bronze badges

5

Under «Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions» add _CRT_SECURE_NO_WARNINGS

answered Feb 15, 2015 at 10:59

nexusclarum's user avatar

nexusclarumnexusclarum

9611 gold badge6 silver badges3 bronze badges

0

If your are in Visual Studio 2012 or later this has an additional setting ‘SDL checks’ Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES — For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

answered Mar 20, 2015 at 16:05

kmcnamee's user avatar

kmcnameekmcnamee

5,0772 gold badges25 silver badges36 bronze badges

1

For a quick fix or test, I find it handy just adding #define _CRT_SECURE_NO_WARNINGS to the top of the file before all #include

#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
    //...
}

Ru Chern Chong's user avatar

answered Apr 14, 2019 at 16:22

Carlosio's user avatar

CarlosioCarlosio

3993 silver badges6 bronze badges

3

Adding _CRT_SECURE_NO_WARNINGS to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn’t work for me, don’t know why.

The following hint works:
In stdafx.h file, please add

#define _CRT_SECURE_NO_DEPRECATE

before include other header files.

Niall's user avatar

Niall

29.9k10 gold badges98 silver badges141 bronze badges

answered Jan 24, 2019 at 8:39

user2703790's user avatar

Visual Studio 2019 with CMake

Add the following to CMakeLists.txt:

add_definitions(-D_CRT_SECURE_NO_WARNINGS)

answered Jan 17, 2021 at 5:36

rbento's user avatar

rbentorbento

9,5693 gold badges60 silver badges59 bronze badges

1

I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS after #include "pch.h"

#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....

answered Jul 12, 2020 at 9:58

molecoder's user avatar

molecodermolecoder

4231 gold badge7 silver badges24 bronze badges

Visual C++: используем _CRT_SECURE_NO_WARNINGS для совместимости с классическими функциями

Часто жалуются на «неработающие» коды, особенно консольных приложений или CLR, особенно тех, что работали без каких-либо замечаний в версиях 2010-2013 и вдруг «не работают» в 2015, например, вот этот код.

Выдаются ошибки типа

Ошибка C4996 ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Можете, как и рекомендует компилятор,
заменить старые названия функций на их безопасные версии, скажем,
strcpy на strcpy_s и
fopen на fopen_s.

Правда, в последнем случае
изменится и «классический» оператор открытия файла, скажем, с

FILE *out = fopen_s("data.txt", "wt");

на

FILE *out; fopen_s(&out,"data.txt", "wt");

Суть дела в том, что функции, возвращающие указатель, считаются небезопасными, отсюда и изменившийся шаблон метода открытия файла.

Есть путь ещё проще — напишите

#define _CRT_SECURE_NO_WARNINGS

в самом начале до всех #include.

Если используется предкомпиляция, то можно определить этот макрос в заголовочном файле stdafx.h.

Можно также попробовать «дорисовать» его не в заголовках, а в настройках проекта.

Управление предкомпилированными заголовками находится вот где: меню Проект — Свойства C/C++ — Препроцессор (Preprocessor) — Определения препроцессора (Preprocessor Definitions).

Проверено на пустом проекте C++ Visual Studio 2015, 2019, сработало.

Некоторым функциям директива «не поможет», например, stricmp всё равно придётся заменять но _stricmp, правда, без изменения списка аргументов.

Заметим, что по стандартам C++ функции strcpy, strcat и другие не устарели, это собственная политика Microsoft.

13.10.2015, 11:48 [99927 просмотров]


К этой статье пока нет комментариев, Ваш будет первым

  • Remove From My Forums
  • Question

  • #include<stdio.h>
    #include<conio.h>
    #define _CRT_SECURE_NO_WARNINGS
    void main(){
    int x,y,temp;
    printf(«Enter two numbers :»);
    scanf(«%d,%d»,&x,&y);
    printf(«nValue before swapping x=%d ,y=%d»,x,y);
    temp=x;
    x=y;
    y=temp;
    printf(«nValue after swapping x=%d ,y=%d»,x,y);

    }

    I have written above pieace of code to simply swap two numbers.

    But is is asking me to use scanf_s instead scanf.Y is it so…?

    Please reply me asap

    • Moved by

      Saturday, September 14, 2013 6:49 AM
      Visual C++ specific

Answers

  • Hi BijalPatel,

    In stdafx.h file, please add «#define_CRT_SECURE_NO_DEPRECATE» before include other header files.

    Also, you can add «_CRT_SECURE_NO_DEPRECATE» in Preprocessor Definitions.

    Right-click your project->Properties->Configuration Properties->Preprocessor->Preprocessor Definitions.


    Sunny Cao
    <THE CONTENT IS PROVIDED «AS IS» WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to «Mark as Answer» the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    • Marked as answer by
      Anna Cc
      Monday, September 23, 2013 1:58 AM

title description ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Warning (level 3) C4996

Explains why Compiler warning C4996 happens, and describes what to do about it.

08/30/2022

C4996

C4996

926c7cc2-921d-43ed-ae75-634f560dd317

Compiler Warning (level 3) C4996

Your code uses a function, class member, variable, or typedef that’s marked deprecated. Symbols are deprecated by using a __declspec(deprecated) modifier, or the C++14 [[deprecated]] attribute. The actual C4996 warning message is specified by the deprecated modifier or attribute of the declaration.

[!IMPORTANT]
This warning is always a deliberate message from the author of the header file that declares the symbol. Don’t use the deprecated symbol without understanding the consequences.

Remarks

Many functions, member functions, function templates, and global variables in Visual Studio libraries are deprecated. Some, such as POSIX and Microsoft-specific functions, are deprecated because they now have a different preferred name. Some C runtime library functions are deprecated because they’re insecure and have a more secure variant. Others are deprecated because they’re obsolete. The deprecation messages usually include a suggested replacement for the deprecated function or global variable.

The /sdl (Enable Additional Security Checks) compiler option elevates this warning to an error.

Turn off the warning

To fix a C4996 issue, we usually recommend you change your code. Use the suggested functions and global variables instead. If you need to use the existing functions or variables for portability reasons, you can turn off the warning.

Turn off the warning for a specific line of code

To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996).

Turn off the warning within a file

To turn off the warning within a file for everything that follows, use the warning pragma, #pragma warning(disable : 4996).

Turn off the warning in command-line builds

To turn off the warning globally in command-line builds, use the /wd4996 command-line option.

Turn off the warning for a project in Visual Studio

To turn off the warning for an entire project in the Visual Studio IDE:

  1. Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

  2. Select the Configuration Properties > C/C++ > Advanced property page.

  3. Edit the Disable Specific Warnings property to add 4996. Choose OK to apply your changes.

Disable the warning using preprocessor macros

You can also use preprocessor macros to turn off certain specific classes of deprecation warnings used in the libraries. These macros are described below.

To define a preprocessor macro in Visual Studio:

  1. Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

  2. Expand Configuration Properties > C/C++ > Preprocessor.

  3. In the Preprocessor Definitions property, add the macro name. Choose OK to save, and then rebuild your project.

To define a macro only in specific source files, add a line such as #define EXAMPLE_MACRO_NAME before any line that includes a header file.

Here are some of the common sources of C4996 warnings and errors:

POSIX function names

The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: new-name. See online help for details.

Microsoft renamed some POSIX and Microsoft-specific library functions in the CRT to conform with C99 and C++03 constraints on reserved and global implementation-defined names. Only the names are deprecated, not the functions themselves. In most cases, a leading underscore was added to the function name to create a conforming name. The compiler issues a deprecation warning for the original function name, and suggests the preferred name.

To fix this issue, we usually recommend you change your code to use the suggested function names instead. However, the updated names are Microsoft-specific. If you need to use the existing function names for portability reasons, you can turn off these warnings. The functions are still available in the library under their original names.

To turn off deprecation warnings for these functions, define the preprocessor macro _CRT_NONSTDC_NO_WARNINGS. You can define this macro at the command line by including the option /D_CRT_NONSTDC_NO_WARNINGS.

Unsafe CRT Library functions

This function or variable may be unsafe. Consider using safe-version instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Microsoft deprecated some CRT and C++ Standard Library functions and globals because more secure versions are available. Most of the deprecated functions allow unchecked read or write access to buffers. Their misuse can lead to serious security issues. The compiler issues a deprecation warning for these functions, and suggests the preferred function.

To fix this issue, we recommend you use the function or variable safe-version instead. Sometimes you can’t, for portability or backwards compatibility reasons. Carefully verify it’s not possible for a buffer overwrite or overread to occur in your code. Then, you can turn off the warning.

To turn off deprecation warnings for these functions in the CRT, define _CRT_SECURE_NO_WARNINGS.

To turn off warnings about deprecated global variables, define _CRT_SECURE_NO_WARNINGS_GLOBALS.

For more information about these deprecated functions and globals, see Security Features in the CRT and Safe Libraries: C++ Standard Library.

Unsafe Standard Library functions

'std:: function_name ::_Unchecked_iterators::_Deprecate' Call to std:: function_name with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'

In Visual Studio 2015, this warning appears in debug builds because certain C++ Standard Library function templates don’t check parameters for correctness. Often it’s because not enough information is available to the function to check container bounds. Or, because iterators may be used incorrectly with the function. This warning helps you identify these functions, because they may be a source of serious security holes in your program. For more information, see Checked iterators.

For example, this warning appears in Debug mode if you pass an element pointer to std::copy, instead of a plain array. To fix this issue, use an appropriately declared array, so the library can check the array extents and do bounds checking.

// C4996_copyarray.cpp
// compile with: cl /c /W4 /D_DEBUG C4996_copyarray.cpp
#include <algorithm>

void example(char const * const src) {
    char dest[1234];
    char * pdest3 = dest + 3;
    std::copy(src, src + 42, pdest3); // C4996
    std::copy(src, src + 42, dest);   // OK, copy can tell that dest is 1234 elements
}

Several standard library algorithms were updated to have «dual range» versions in C++14. If you use the dual range versions, the second range provides the necessary bounds checking:

// C4996_containers.cpp
// compile with: cl /c /W4 /D_DEBUG C4996_containers.cpp
#include <algorithm>

bool example(
    char const * const left,
    const size_t leftSize,
    char const * const right,
    const size_t rightSize)
{
    bool result = false;
    result = std::equal(left, left + leftSize, right); // C4996
    // To fix, try this form instead:
    // result = std::equal(left, left + leftSize, right, right + rightSize); // OK
    return result;
}

This example demonstrates several more ways the standard library may be used to check iterator usage, and when unchecked usage may be dangerous:

// C4996_standard.cpp
// compile with: cl /EHsc /W4 /MDd C4996_standard.cpp
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }

    cout << endl;
}

int main()
{
    vector<int> v(16);
    iota(v.begin(), v.end(), 0);
    print("v: ", v);

    // OK: vector::iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    vector<int> v2(16);
    transform(v.begin(), v.end(), v2.begin(), [](int n) { return n * 2; });
    print("v2: ", v2);

    // OK: back_insert_iterator is marked as checked in debug mode
    // (i.e. an overrun is impossible)
    vector<int> v3;
    transform(v.begin(), v.end(), back_inserter(v3), [](int n) { return n * 3; });
    print("v3: ", v3);

    // OK: array::iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    array<int, 16> a4;
    transform(v.begin(), v.end(), a4.begin(), [](int n) { return n * 4; });
    print("a4: ", a4);

    // OK: Raw arrays are checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    // NOTE: This applies only when raw arrays are
    // given to C++ Standard Library algorithms!
    int a5[16];
    transform(v.begin(), v.end(), a5, [](int n) { return n * 5; });
    print("a5: ", a5);

    // WARNING C4996: Pointers cannot be checked in debug mode
    // (i.e. an overrun triggers undefined behavior)
    int a6[16];
    int * p6 = a6;
    transform(v.begin(), v.end(), p6, [](int n) { return n * 6; });
    print("a6: ", a6);

    // OK: stdext::checked_array_iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    int a7[16];
    int * p7 = a7;
    transform(v.begin(), v.end(),
        stdext::make_checked_array_iterator(p7, 16),
        [](int n) { return n * 7; });
    print("a7: ", a7);

    // WARNING SILENCED: stdext::unchecked_array_iterator
    // is marked as checked in debug mode, but it performs no checking,
    // so an overrun triggers undefined behavior
    int a8[16];
    int * p8 = a8;
    transform( v.begin(), v.end(),
        stdext::make_unchecked_array_iterator(p8),
        [](int n) { return n * 8; });
    print("a8: ", a8);
}

If you’ve verified that your code can’t have a buffer-overrun error, you can turn off this warning. To turn off warnings for these functions, define _SCL_SECURE_NO_WARNINGS.

Checked iterators enabled

C4996 can also occur if you don’t use a checked iterator when _ITERATOR_DEBUG_LEVEL is defined as 1 or 2. It’s set to 2 by default for debug mode builds, and to 0 for retail builds. For more information, see Checked iterators.

// C4996_checked.cpp
// compile with: /EHsc /W4 /MDd C4996_checked.cpp
#define _ITERATOR_DEBUG_LEVEL 2

#include <algorithm>
#include <iterator>

using namespace std;
using namespace stdext;

int main() {
    int a[] = { 1, 2, 3 };
    int b[] = { 10, 11, 12 };
    copy(a, a + 3, b + 1);   // C4996
    // try the following line instead:
    // copy(a, a + 3, checked_array_iterator<int *>(b, 3));   // OK
}

Unsafe MFC or ATL code

C4996 can occur if you use MFC or ATL functions that were deprecated for security reasons.

To fix this issue, we strongly recommend you change your code to use updated functions instead.

For information on how to suppress these warnings, see _AFX_SECURE_NO_WARNINGS.

Obsolete CRT functions and variables

This function or variable has been superseded by newer library or operating system functionality. Consider using new_item instead. See online help for details.

Some library functions and global variables are deprecated as obsolete. These functions and variables may be removed in a future version of the library. The compiler issues a deprecation warning for these items, and suggests the preferred alternative.

To fix this issue, we recommend you change your code to use the suggested function or variable.

To turn off deprecation warnings for these items, define _CRT_OBSOLETE_NO_WARNINGS. For more information, see the documentation for the deprecated function or variable.

Marshaling errors in CLR code

C4996 can also occur when you use the CLR marshaling library. In this case, C4996 is an error, not a warning. The error occurs when you use marshal_as to convert between two data types that require a marshal_context Class. You can also receive this error when the marshaling library doesn’t support a conversion. For more information about the marshaling library, see Overview of marshaling in C++.

This example generates C4996 because the marshaling library requires a context to convert from a System::String to a const char *.

// C4996_Marshal.cpp
// compile with: /clr
// C4996 expected
#include <stdlib.h>
#include <string.h>
#include <msclrmarshal.h>

using namespace System;
using namespace msclr::interop;

int main() {
   String^ message = gcnew String("Test String to Marshal");
   const char* result;
   result = marshal_as<const char*>( message );
   return 0;
}

Example: User-defined deprecated function

You can use the deprecated attribute in your own code to warn callers when you no longer recommend use of certain functions. In this example, C4996 is generated in two places: One for the line the deprecated function is declared on, and one for the line where the function is used.

// C4996.cpp
// compile with: /W3
// C4996 warning expected
#include <stdio.h>

// #pragma warning(disable : 4996)
void func1(void) {
   printf_s("nIn func1");
}

[[deprecated]]
void func1(int) {
   printf_s("nIn func2");
}

int main() {
   func1();
   func1(1);    // C4996
}

I have compile error in my simple MFC window application generated from wizard with several lines of code:

error C4996: ‘strncpy’: This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

I set Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_NONSTDC_NO_WARNINGS

But this does’t helped. I have another very close project that generates only warning in this place and it has no _CRT_NONSTDC_NO_WARNINGS definition.

Only difference between projects is several different options in wizard.

Why _CRT_NONSTDC_NO_WARNINGS does not helps in first project and why second project compiles without problems without this definition?

SOLUTION 1 :

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

SOLUTION 2 :

Under «Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions» add _CRT_SECURE_NO_WARNINGS

SOLUTION 3 :

If your are in Visual Studio 2012 or later this has an additional setting ‘SDL checks’ Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES — For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

SOLUTION 4 :

Adding _CRT_SECURE_NO_WARNINGS to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn’t work for me, don’t know why.

The following hint works: In stdafx.h file, please add «#define_CRT_SECURE_NO_DEPRECATE» before include other header files.

SOLUTION 5 :

For a quick fix or test I find it handy just adding #define _CRT_SECURE_NO_WARNINGS to the top of the file before all #include

#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
//...
}

Label : tag_c++ tag_visual-c++ tag_visual-studio-2012 tag_warnings

  • Crossroads inn ошибка при запуске не является приложением win32
  • Crossout ошибка чтения записи файла
  • Crossout ошибка при входе
  • Crossout ошибка запуска служба easyanticheat не установлена
  • Crossout ошибка 52 fenrir