Disable error c4996

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
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

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
}

In previous versions of Visual Studio using functions like _sleep or strncpy just outputs a warning. In the latest version, it’s suddenly an error:

unexpected error

error C4996: ‘_sleep’: This function or variable has been superseded
by newer library or operating system functionality. Consider using
Sleep instead. See online help for details.

I know I can disable it by adding #pragma warning(disable: 4996) in the beginning of the code, but it’s extremely annoying that VS is trying to force me to use other functions. Is there any way to disable this behavior?

Before you ask, «Treat Warnings As Errors» is disabled, and it errors even if I turn off all warnings!

anastaciu's user avatar

anastaciu

23.1k7 gold badges27 silver badges48 bronze badges

asked Dec 7, 2013 at 23:39

Nikolai's user avatar

3

Apparently new projects enable «SDK check» by default now, which treats these warnings as errors. To disable it, go to project properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No.

answered Dec 7, 2013 at 23:45

Nikolai's user avatar

NikolaiNikolai

2,9733 gold badges24 silver badges33 bronze badges

2

enter at the beginning of the program:

#pragma warning(disable : 4996)

and that’s it.

answered Feb 27, 2018 at 19:16

ניתאי דרעי's user avatar

ניתאי דרעיניתאי דרעי

1632 silver badges9 bronze badges

1

You can also disable specific warning numbers in C/C++ > Advanced > Disable Specific Warnings.

answered Jun 17, 2014 at 15:57

Peter Tseng's user avatar

Peter TsengPeter Tseng

13.3k3 gold badges65 silver badges57 bronze badges

Just to add to this, _CRT_NONSTDC_NO_DEPRECATE worked for me in VS2019. _CRT_SECURE_NO_WARNINGS alone did not clear this for me (I have both defined).

Similar to the other answers, this may be added by right-clicking the project in Solution Explorer, Then going to Properties->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions->Edit… then adding the line _CRT_NONSTDC_NO_DEPRECATE.

answered Jul 4, 2020 at 0:16

Travis Vroman's user avatar

Project ->project_name properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions -> Edit… add line _CRT_SECURE_NO_WARNINGS

answered Jan 5, 2017 at 20:47

Adam G.'s user avatar

Adam G.Adam G.

711 silver badge10 bronze badges

Gusev

0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

1

29.01.2015, 21:33. Показов 32447. Ответов 15

Метки нет (Все метки)


Здравствуйте, у меня показывать ошибку C4996: ‘fopen’. помогите исправить.
Вот код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "stdafx.h"
#include <iostream>
 
const int M = 50; //максмальное количество строк
const int N = 50; //максимальное количество столбцов
 
int main(int argc, char** argv) {
 
    setlocale(0, "rus"); //установка русскоязычной локации
 
    int m, n, k, sum, msum; //описываем переменные
    int a[M][N]; //описываем двумерный массив
    char c;
 
    FILE * file = fopen("test.txt", "r"); //объявляем файловую переменную, связываем с файлом и открываем для чтения
 
    m = 0; //инициализируем переменны
    n = 0;
    while (fscanf(file, "%i%c", &a[m][n], &c) != EOF) //читаем данные пока не конец файла
    {
 
        if (c == 'n') //если конец строки
        {
            m++; //переходим к следующей строке
            n = 0;
        }
        else
            n++; //переходим к следующему столбцу
    }
    m++;
    fclose(file); //закрываем файл
 
    for (int i = 0; i < m; i++) //проход по строкам
    {
        for (int j = 0; j < n; j++) //проход по столбцам
            printf("%4i", a[i][j]); //вывод на экран
        printf("n"); //переход на новую строку
    }
 
    msum = 10000; //начальная минимальня сумма
 
    for (int i = 1; i < m; i += 2) //проход по строкам
    {
        sum = 0; //обнуляем сумму
        for (int j = 0; j < n; j++) //проход по столбцам
            if (a[i][j] % 2 != 0) //проверка на чётность
                sum += a[i][j]; //накопление суммы
        printf("Сумма нечётных элементов в %i-й строке: %in", i + 1, sum); //переход на новую строку
        if (sum < msum)
        {
            msum = sum; //запоминаем текущую сумму
            k = i + 1; //запоминаем текущую строку
        }
    }
    printf("Минимальная сумма нечётных элементов в %i-й строке. n", k);
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



zss

Модератор

Эксперт С++

12640 / 10134 / 6102

Регистрация: 18.12.2011

Сообщений: 27,170

29.01.2015, 21:39

2

C++
1
#pragma warning(disable:4996)



2



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

29.01.2015, 21:41

3

<cstdio> подключи.



0



1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

29.01.2015, 21:41

4

вообще нужно полный текст ошибок/предупреждений приводить.
а перед этим прочитать. там все понятно написано что произошло и как с этим бороться
(по крайней мере для C4996)



0



0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

29.01.2015, 21:43

 [ТС]

5

#pragma warning(disable:4996) и <cstdio> не помогли, как и #define _CRT_SECURE_NO_WARNINGS. а если fopen заменить на fopen_s, то пишет, что fopen_s не может принимать два значения.

Добавлено через 1 минуту
полный текст ошибки: 1>c:usersниколайdocumentsvisual studio 2013projectsconsoleapplication8consoleapplicati on8consoleapplication8.cpp(18): error C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:program files (x86)microsoft visual studio 12.0vcincludestdio.h(211) : see declaration of ‘fopen’



0



1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

29.01.2015, 21:43

6

наверно потому, что оно принимает три:
https://msdn.microsoft.com/ru-… h6ee9.aspx

_CRT_SECURE_NO_WARNINGS — вот это вы где задефайнили? надо чтобы перед инклудом это было.
в вашем случае наверно это прям перед stdafx



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

29.01.2015, 21:45

7

В свойствах проекта уровень предупреждений поменяй.



1



0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

29.01.2015, 21:47

 [ТС]

8

DU2, так я и перед инклудами писал, выдает еще одну ошибку warning C4603: ‘_CRT_SECURE_NO_WARNINGS’ : macro is not defined or definition is different after precompiled header use
Add macro to precompiled header instead of defining here



0



DU

1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

29.01.2015, 21:49

9

C++
1
2
3
4
5
#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include <iostream>
 
...

так? если так и все равно проблемы — тогда хз.
пробуйте в свойствах проекта выставить:
Project->PRoperties->C/C++->Preprocessor->Preprocessor Definitions
туда этот макрос напишите.



1



0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

29.01.2015, 22:06

 [ТС]

10

nmcf, а как это сделать? у меня английская версия, плохо понимаю.

Добавлено через 15 минут
В общем в свойствах проекта прописал макрос — не помогло. Поменял уровень предупреждений — не помогло



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

29.01.2015, 22:26

11

В разделе C/C++ — обрабатывать предупреждения как ошибки — Нет.



0



1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

29.01.2015, 22:38

12

какая у вас студия?
запакуйте все проектные файлы и сюда выложите чтоли.



0



0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

29.01.2015, 22:46

 [ТС]

13



0



1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

29.01.2015, 23:01

14

Лучший ответ Сообщение было отмечено Gusev как решение

Решение

В свойствах:
Project->Properties->Configuration Properties->C/C++->General->SDL checks
поставте в No
это превратит ошибку в ворнинг, которая отключается если сильно надо одним из ранее описанных способов:
макросом в свойствах или макросом в коде.



3



0 / 0 / 0

Регистрация: 04.12.2014

Сообщений: 10

29.01.2015, 23:19

 [ТС]

15

а теперь выводит вот это http://rghost.ru/8J7k4jhT5

Добавлено через 3 минуты
похоже, что это у меня в VS проблема.
DU2, спасибо.



0



1499 / 1145 / 165

Регистрация: 05.12.2011

Сообщений: 2,279

30.01.2015, 00:03

16

это у вас рантайм ошибка. глюк в коде, а не в студии.
осваивайте студийных дебаггер.
начать можно отсюда:
https://www.cyberforum.ru/cpp-… 62479.html



0



Содержание

  1. Compiler Warning (level 3) C4996
  2. Remarks
  3. Turn off the warning
  4. Turn off the warning for a specific line of code
  5. Turn off the warning within a file
  6. Turn off the warning in command-line builds
  7. Turn off the warning for a project in Visual Studio
  8. Disable the warning using preprocessor macros
  9. POSIX function names
  10. Unsafe CRT Library functions
  11. Unsafe Standard Library functions
  12. Checked iterators enabled
  13. Unsafe MFC or ATL code
  14. Obsolete CRT functions and variables
  15. Marshaling errors in CLR code
  16. Example: User-defined deprecated function
  17. Предупреждение компилятора (уровень 3) C4996
  18. Комментарии
  19. Отключение предупреждения
  20. Отключение предупреждения для определенной строки кода
  21. Отключение предупреждения в файле
  22. Отключение предупреждения в сборках командной строки
  23. Отключение предупреждения для проекта в Visual Studio
  24. Отключение предупреждения с помощью макросов препроцессора
  25. Имена функций POSIX
  26. Небезопасные функции библиотеки CRT
  27. Небезопасные функции стандартной библиотеки
  28. Проверенные итераторы включены
  29. Небезопасный код MFC или ATL
  30. Устаревшие функции и переменные CRT
  31. Маршалинг ошибок в коде СРЕДЫ CLR
  32. Пример: определяемая пользователем нерекомендуемая функция

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.

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.

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:

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

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

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:

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

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

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.

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:

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

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.

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 * .

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.

Источник

Предупреждение компилятора (уровень 3) C4996

Код использует функцию, член класса, переменную или определение типа, помеченную как нерекомендуемую. Символы устарели с помощью __declspec(deprecated) модификатора или атрибута C++14 [[deprecated]] . Фактическое предупреждающее сообщение C4996 задается модификатором или атрибутом deprecated объявления.

Это предупреждение всегда является преднамеренным сообщением автора файла заголовка, объявляющего символ. Не используйте устаревший символ без понимания последствий.

Комментарии

Многие функции, функции-члены, шаблоны функций и глобальные переменные в библиотеках Visual Studio устарели. Некоторые функции, такие как POSIX и функции Майкрософт, устарели, так как теперь они имеют другое предпочтительное имя. Некоторые функции библиотеки среды выполнения C устарели, так как они небезопасны и имеют более безопасный вариант. Другие нерекомендуемые, так как они устарели. Сообщения об устаревании обычно включают предполагаемую замену устаревшей функции или глобальной переменной.

Отключение предупреждения

Чтобы устранить проблему C4996, обычно рекомендуется изменить код. Вместо этого используйте предлагаемые функции и глобальные переменные. Если вам нужно использовать существующие функции или переменные по соображениям переносимости, можно отключить предупреждение.

Отключение предупреждения для определенной строки кода

Чтобы отключить предупреждение для определенной строки кода, используйте директиву warning pragma. #pragma warning(suppress : 4996)

Отключение предупреждения в файле

Чтобы отключить предупреждение в файле для всего следующего, используйте директиву pragma #pragma warning(disable : 4996) предупреждения.

Отключение предупреждения в сборках командной строки

Чтобы отключить предупреждение глобально в сборках командной строки, используйте параметр командной /wd4996 строки.

Отключение предупреждения для проекта в Visual Studio

Чтобы отключить предупреждение для всего проекта в интегрированной среде разработки Visual Studio, выполните следующие действия.

Откройте диалоговое окно «Страницы свойств » для проекта. Сведения об использовании диалогового окна «Страницы свойств» см. в разделе «Страницы свойств».

Выберите страницу свойств> конфигурацииC/C++>Advanced.

Измените свойство Disable Specific Warnings для добавления 4996 . Нажмите кнопку «ОК» , чтобы применить изменения.

Отключение предупреждения с помощью макросов препроцессора

Вы также можете использовать макросы препроцессора для отключения определенных классов предупреждений об устаревании, используемых в библиотеках. Эти макросы описаны ниже.

Чтобы определить макрос препроцессора в Visual Studio, выполните следующие действия.

Откройте диалоговое окно «Страницы свойств » для проекта. Сведения об использовании диалогового окна «Страницы свойств» см. в разделе «Страницы свойств».

Разверните свойства > конфигурации препроцессора C/C++>.

В свойстве «Определения препроцессора» добавьте имя макроса. Нажмите кнопку ОК для сохранения изменений, а затем выполните повторную сборку проекта.

Чтобы определить макрос только в определенных исходных файлах, добавьте строку, #define EXAMPLE_MACRO_NAME например перед любой строкой, включающей файл заголовка.

Ниже приведены некоторые распространенные источники предупреждений и ошибок C4996:

Имена функций POSIX

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

Корпорация Майкрософт переименовывает некоторые функции БИБЛИОТЕК POSIX и Microsoft в CRT в соответствии с ограничениями C99 и C++03 для зарезервированных и глобальных имен, определенных реализацией. Не рекомендуется использовать только имена, а не сами функции. В большинстве случаев в имя функции был добавлен символ подчеркивания, чтобы создать соответствующее имя. Компилятор выдает предупреждение об устаревании для исходного имени функции и предлагает предпочтительное имя.

Чтобы устранить эту проблему, мы обычно рекомендуем изменить код, чтобы использовать предлагаемые имена функций. Однако обновленные имена зависят от корпорации Майкрософт. Если вам нужно использовать существующие имена функций по причинам переносимости, эти предупреждения можно отключить. Функции по-прежнему доступны в библиотеке под их исходными именами.

Чтобы отключить предупреждения об устаревании для этих функций, определите макрос _CRT_NONSTDC_NO_WARNINGS препроцессора. Этот макрос можно определить в командной строке, включив параметр /D_CRT_NONSTDC_NO_WARNINGS .

Небезопасные функции библиотеки CRT

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.

Корпорация Майкрософт не рекомендует использовать некоторые функции стандартной библиотеки CRT и C++, так как доступны более безопасные версии. Большинство устаревших функций позволяют отменить доступ на чтение или запись к буферам. Их неправильное использование может привести к серьезным проблемам безопасности. Компилятор выдает предупреждение об устаревании для этих функций и предлагает предпочтительную функцию.

Чтобы устранить эту проблему, рекомендуется использовать вместо нее функцию или переменную safe-version . Иногда невозможно, по соображениям переносимости или обратной совместимости. Тщательно убедитесь, что в коде невозможно перезаписать или перечитать буфер. Затем можно отключить предупреждение.

Чтобы отключить предупреждения об устаревании для этих функций в CRT, определите _CRT_SECURE_NO_WARNINGS .

Чтобы отключить предупреждения о нерекомендуемых глобальных переменных, определите _CRT_SECURE_NO_WARNINGS_GLOBALS .

Дополнительные сведения об этих устаревших функциях и глобальных функциях см. в разделе «Функции безопасности» в CRT и безопасных библиотеках: стандартная библиотека C++.

Небезопасные функции стандартной библиотеки

‘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’

В Visual Studio 2015 это предупреждение отображается в отладочных сборках, так как некоторые шаблоны функций стандартной библиотеки C++ не проверяют правильность параметров. Часто это связано с тем, что функции недостаточно информации для проверки границ контейнера. Или, поскольку итераторы могут использоваться неправильно с функцией. Это предупреждение помогает определить эти функции, так как они могут быть источником серьезных дыр в вашей программе. Дополнительные сведения см. в разделе «Проверенные итераторы».

Например, это предупреждение отображается в режиме отладки при передаче указателя std::copy на элемент вместо обычного массива. Чтобы устранить эту проблему, используйте соответствующий объявленный массив, чтобы библиотека может проверить экстенты массива и выполнить проверку границ.

В C++14 были обновлены несколько стандартных алгоритмов библиотеки с версиями «двойного диапазона». При использовании версий двойного диапазона второй диапазон обеспечивает необходимую проверку границ:

В этом примере показано несколько других способов использования стандартной библиотеки для проверки использования итератора, а также если флажок использования может быть опасным:

Если вы убедились, что код не может иметь ошибку переполнения буфера, вы можете отключить это предупреждение. Чтобы отключить предупреждения для этих функций, определите _SCL_SECURE_NO_WARNINGS .

Проверенные итераторы включены

C4996 также может возникнуть, если вы не используете проверяемый итератор, если _ITERATOR_DEBUG_LEVEL он определен как 1 или 2. По умолчанию для сборок в режиме отладки установлено значение 2, а для розничных сборок — значение 0. Дополнительные сведения см. в разделе «Проверенные итераторы».

Небезопасный код MFC или ATL

C4996 может возникнуть, если вы используете функции MFC или ATL, которые были нерекомендуемые по соображениям безопасности.

Чтобы устранить эту проблему, настоятельно рекомендуется изменить код для использования обновленных функций.

Сведения о том, как отключить эти предупреждения, см. в разделе _AFX_SECURE_NO_WARNINGS .

Устаревшие функции и переменные CRT

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

Некоторые функции и глобальные переменные библиотеки устарели. Эти функции и переменные могут быть удалены в будущей версии библиотеки. Компилятор выдает предупреждение об устаревании для этих элементов и предлагает предпочтительную альтернативу.

Чтобы устранить эту проблему, рекомендуется изменить код на использование предлагаемой функции или переменной.

Чтобы отключить предупреждения об устаревании для этих элементов, определите _CRT_OBSOLETE_NO_WARNINGS . Дополнительные сведения см. в документации по устаревшей функции или переменной.

Маршалинг ошибок в коде СРЕДЫ CLR

C4996 также может возникать при использовании библиотеки маршалинга CLR. В этом случае C4996 является ошибкой, а не предупреждением. Эта ошибка возникает при marshal_as преобразовании между двумя типами данных, которым требуется marshal_context класс. Эту ошибку также можно получить, если библиотека маршалинга не поддерживает преобразование. Дополнительные сведения о библиотеке маршалинга см. в обзоре маршалинга в C++.

В этом примере возникает ошибка C4996, так как для библиотеки маршалинга требуется контекст для преобразования из a System::String в . const char *

Пример: определяемая пользователем нерекомендуемая функция

Атрибут можно использовать в собственном коде deprecated , чтобы предупреждать вызывающих объектов, если вы больше не рекомендуете использовать определенные функции. В этом примере C4996 создается в двух местах: одна для строки, в которой объявлена нерекомендуемая функция, и одна для строки, в которой используется функция.

Источник

  • Remove From My Forums
  • Question

  • Hi everyone,

    How do you disable the deprecation check in VC++ Express Edition?

    Below is what I’m trying to do:

    Code Snippet

    warning 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.

    How/where do I use _CRT_SECURE_NO_WARNINGS ?

    I’m looking into using strcpy_s at the moment, but I would like to know the method to disable the warning, just to learn.

    Thanks in advance!!

    Kurt

Answers

  • Allways happy to help a fellow wrestler…

    Project properties->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions

    Click on the elipses (…)
    type any definitions you like separated by «n»ie

    _CRT_SECURE_NO_WARNINGS

    hit OK.
    enjoy the silence…

    Robin

Introduction

Two programmers went to buy cigarettes. One buys them and goes “Dude, did you read this? Warning! Smoking causes lung cancer witch is fatal”. Then the other one says “Yeah, forget the warning, just tell me the errors!”

When using Microsoft Visual Studio 2005 or newer, the compiler may give a bunch of annoying warnings saying something like: “warning 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”. CRT functions like strcpy are standard functions, so why the compiler complains? Well, it simply recommends using of more secure versions of CRT functions which have ‘_s’ postfix (strcpy_s instead of strcpy, sprintf_s instead of sprintf and so on). So, at a first look nothing fatal happened and we can go ahead. However, simply ignoring the warnings is not a good practice and moreover someone may work in a company or project in which “zero warnings” is a must.

This article is about how to deal with C4996 warning, what secure CRT functions are and how to correctly use them. Further, let’s call them “_s functions”.

Can we get rid of C4996 warnings?

Especially when porting code written under an older Visual C++ version, we may want to get rid of C4996 warnings. The answer is: yes, we can like in case of other compiler warnings, by adding pragma warning directive in the source code.

#pragma warning(disable: 4996)

You may add pragma warning in each source file or, if the project uses precompiled header, adding only it in StdAfx.h is pretty enough.

Another and better way is to add _CRT_SECURE_NO_WARNINGS to preprocessor definitions, as suggested in the description of the warning. To find out how to add _CRT_SECURE_NO_WARNINGS, take a look in MSDN at /D (Preprocessor Definitions).

No warnings, no more headaches, and the boss is happy. However, please read further! One good way to avoid C4996 warnings is… by using _s functions.

Why using _s functions?

Here, I would like to quote from one of Michael Howard’s articles:

Think about it for a moment. When were functions like strcpy and strcat invented? They were designed in happier times when the C language was first developed by Kernighan and Ritchie long ago, when threats were by no means as serious as they are today, and when networking wasn’t as pervasive as it is today. Now don’t get me wrong, you can write secure code with functions like strcpy. It’s the data that’s the culprit, after all. But functions like strcpy don’t help you write secure code, and an error in such a function can be catastrophic. Of course, gets is just plain evil! ‘Nuff said.

I heard C/C++ programmers saying: “I’ve never ever made a bug”. That’s pretty possible if they never ever made a line of code. Otherwise, I can’t believe them. Nobody is perfect and everyone can do mistakes.
In the first side, standard C functions were designed for speed. For that reason, they do not perform run-time checking which is usually performed in other programming languages. A programmer must be carefully when use those functions and validate parameters in the own code in order to avoid troubles like buffer overrun, access violation, malicious attacks, and so on.

Well, _s functions do additional checking for you. Details about Security Enhancements in the CRT can be found in MSDN library.
I will give just a trivial example concerning null termination string problem. One can say “this is stupid, something like that can never happen”. Wrong! In the real programming world, other ones even more stupid, much more insidious and having uglier effects, can be found.

Two strings walk into a bar. One of them says: “A beer, please!%@8Hj(^&9))%@!$%*” The other one says: “You’ll have to excuse my friend, he is not zero-terminated.”

May be a good programmers’ joke, but in a C/C++ application, a not-zero terminated string is not so funny. Let’s try translating it into code:

#define MAX_BUFFER 1000
void append_joke(char* buff, const char* psz)
{
   strcat(buff, psz); // classic
}

int main()
{
   char* joke = new char[MAX_BUFFER];
   memcpy(joke, "A beer, please!", strlen("A beer, please!"));
   append_joke(joke, "You'll have to excuse my friend…");
   printf(joke);
   delete []joke;
#ifdef _DEBUG
   system("pause");
#endif
   return 0;
}

If the program doesn’t crash (here because of heap corruption) we can’t say that we are lucky. The result may be a bunch of garbage like in the above joke. But if we use strcat_s instead of strcat, a run-time checking against not properly null terminated string will be performed. Further we’ll see what’s happen in this case.

Do _s functions prevent program crashing?

Most of programmers dealing first time with _s functions think that program will never crash even they are doing mistakes. In other words, simply replacing standard CRT functions with more secure ones, prevents application crashing. That is not true. Let’s modify append_joke function and replace strcat with “more secure” strcat_s.

void append_joke(char* buff, const char* psz)
{
   strcat_s(buff, MAX_BUFFER, psz); // more secure
}

Now, let’s run again the program in debug mode. Oups!.. A “Debug Assertion Failed” message box is shown. If press “Ignore” button, another “fatal error” message is shown then program terminates. What happened? First, strcat_s function checks parameters validity. If one is invalid (in our example we have not null terminated string) and if the program runs in debug mode, a “debug assertion failed” message is shown. That’s very good, because we have a chance to fix the mistake, first looking at assertion message (here is “String is not null terminated”), then pressing “Retry” and search the source of error in “Call Stack” window. That is not possible in case of using the “classic” function strcat.
Finally, an invalid parameter handler function is called and the process terminates. That’s also good because, if something is really going bad, it’s preferable to close the application instead of let it doing unpredictable things.

How to customize the _s functions behavior?

As stated above, when _s functions detect an invalid parameter, a message is shown then the application process terminates.
However, someone may want to do something else before application exits or simply wants application to continue. Someone else may wonder why the _s functions return an error code as long as by default, if an invalid parameter is passed, the process is terminated. Well, the default invalid parameter handler function may be replaced with an application-defined one. For doing that, we can call _set_invalid_parameter_handler function.

Here is an example. It prevents showing the debug assertion failure message and sets an application-defined invalid parameter handler function. In case that invalid parameter is passed, the process isn’t terminated. Also, the error code returned by strcat_s is used by program, which prints out the string only if it’s Ok.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h>

void app_handler(const wchar_t * expression,
                 const wchar_t * function,
                 const wchar_t * file,
                 unsigned int line,
                 uintptr_t pReserved)
{
   wprintf_s(L"%snFunction:%snFile:%snLine:%un",
             expression, function, file, line);
}

#define MAX_BUFFER 1000
errno_t finish_joke(char* buff, const char* psz)
{
   return strcat_s(buff, MAX_BUFFER, psz);
}

int main()
{
   // prevent showing "debug assertion failed" dialog box
   _CrtSetReportMode(_CRT_ASSERT, 0);
    // set application-defined invalid parameter handler
   _set_invalid_parameter_handler(app_handler);

   char* joke = new char[MAX_BUFFER];
   memcpy(joke, "A beer, please!", strlen("A beer, please!"));
   errno_t ret = finish_joke(joke, "You'll have to excuse my friend…");
   if(0 == ret) // prints only if finish_joke succeeded
   {
      printf_s(joke);
   }
   delete []joke;
#ifdef _DEBUG
   system("pause");
#endif
   return 0;
}

Conclusion

  • It’s no sweat to get rid of C4996 warnings but also it’s good to know that secure CRT functions are great.
  • Secure CRT functions perform run-time parameters checking which helps to find mistakes and prevent troubles.
  • The default invalid parameter handler terminates the aplication process; if we want to change this, we have to use an application-defined handler.
  • Last but not the least: if you want to write more solid and secure code, prefer using secure version of CRT functions!

See also

  • MSDN: Security Enhancements in the CRT
  • Michael Howard: Saying Goodbye to an Old Friend
  • Secure CRT Functions Standard

Compile the C language project in VS, if the scanf function is used, the following error will be prompted when compiling:

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

The reason is that Visual C++ uses more secure run-time library routines. The new Security CRT functions (that is, those with the “_s” suffix), please see

“Security Enhanced Version of CRT Function”

The solution to this problem is given below:

Method 1 : Replace the original old functions with new Security CRT functions.

Method 2 : Use the following methods to block this warning:

  1. Define the following macros in the precompiled header file stdafx.h (note: it must be before including any header files):
#define _CRT_SECURE_NO_DEPRECATE
  1. Or statement
#pragma warning(disable:4996)
  1. Change the preprocessing definition:

    Project -> Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definition, add:

_CRT_SECURE_NO_DEPRECATE

Method three : Method two does not use the more secure CRT function, which is obviously not a good method worth recommending, but we don’t want to change the function names one by one. Here is an easier method:

Define the following macros in the precompiled header file stdafx.h (also before including any header files):

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1

When linking, it will automatically replace the old functions with Security CRT functions.

Note: Although this method uses a new function, it cannot eliminate the warning. You have to use method two (-_-) at the same time. In other words, the following two sentences should actually be added to the precompiled header file stdafx.h:

#define _CRT_SECURE_NO_DEPRECATE

#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1

Explanation of the cause of the error:

This kind of warning from Microsoft is mainly because of the functions of the C library. Many functions do not perform parameter detection (including out-of-bounds). Microsoft is worried that using these will cause memory exceptions, so it rewrites the functions of the same function. The function of has carried out parameter detection, and it is safer and more convenient to use these new functions. You don’t need to memorize these rewritten functions specifically, because the compiler will tell you the corresponding safe function when it gives a warning for each function. You can get it by checking the warning message. You can also check MSDN for details when you use it.

Similar Posts:

2 Августа 2017

Время чтения: 5 минут

Visual Studio unsafe error скриншот

Компилятор в Visual Studio сильно отличается от привычных большинству программистов GCC или CLANG, из-за чего при написании кода на C или C++ очень часто возникают неожиданные проблемы в виде ошибки использования стандартных функций, например, scanf, fopen, sscanf и тому подобным. Студия предлагает заменять функции на безопасные (повезёт, если нужно просто добавить _s к функции с ошибкой, но нередко в этих функциях идёт иной набор аргументов, нежели в обычной программе). Если вы не готовы с этим мириться, то этот пост для вас!

Давайте для начала создадим обычный консольный проект в Visual Studio и напишем простенькую программу, которая запрашивает ввод двух чисел, вводит их и затем выводит на экран.

#include "stdafx.h"
#include <stdio.h>

int main() {
	int a, b;

	printf("Enter a: ");
	scanf("%d", &a);

	printf("Enter b: ");
	scanf("%d", &b);

	printf("a: %d, b: %dn", a, b);
	return 0;
}

Попробовав выполнить сборку проекта, обнаружим те самые ошибки.

Чтобы Visual Studio не тратила ваши нервы, сделаем следующее:

1. Выберем пункт «Проект» в верхнем меню

2. В открывшемся списке щёлкнем по «Свойства название_проекта»

Программа, вводящая два числа и выводящая их

Программа, вводящая два числа и выводящая их

Ошибка компиляции из-за небезопасности функций

Ошибка компиляции из-за небезопасности функций

Проект -> Свойства {навание проекта}

Проект — Свойства {навание проекта}

3. В появившемся окне выберем Свойства конфигурации, C/C++, Препроцессор

4. В строке Определения препроцессора допишем в самый конец строку ;_CRT_SECURE_NO_WARNINGS

5. Нажмём ОК

Свойства конфигурации

Свойства конфигурации

Определения препроцессора

Определения препроцессора

OK

Нажимаем OK

6. Попробуем заново выполнить сборку проекта:

Успешная сборка проекта

Успешная сборка проекта

Ошибки исчезли, сборка прошла успешно и программа прекрасно работает! Теперь можно писать код как обычно, не переживая о необычном поведении Visual Studio!

Фото Перминова Андрея, автора этой статьи

Программист, сооснователь programforyou.ru, в постоянном поиске новых задач и алгоритмов

Языки программирования: Python, C, C++, Pascal, C#, Javascript

Выпускник МГУ им. М.В. Ломоносова

Понравилась статья? Поделить с друзьями:
  • Discord error 80070005
  • Discord error 429
  • Disable cache error process terminated
  • Disable bios memory options such as caching or shadowing как исправить windows 7
  • Dis26012 beko ошибка e02