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
1,3172 gold badges15 silver badges30 bronze badges
asked Mar 17, 2014 at 9:15
6
Add by
Configuration Properties>>C/C++>>Preporocessor>>Preprocessor
Definitions>> _CRT_SECURE_NO_WARNINGS
Sumurai8
20.4k11 gold badges66 silver badges100 bronze badges
answered Mar 17, 2014 at 9:37
BaluBalu
2,2571 gold badge18 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
nexusclarumnexusclarum
9711 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
kmcnameekmcnamee
5,1072 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(){
//...
}
answered Apr 14, 2019 at 16:22
CarlosioCarlosio
4094 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
30.1k10 gold badges100 silver badges143 bronze badges
answered Jan 24, 2019 at 8:39
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
rbentorbento
10.1k3 gold badges62 silver badges61 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
molecodermolecoder
4231 gold badge7 silver badges24 bronze badges
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
1,3172 gold badges15 silver badges30 bronze badges
asked Mar 17, 2014 at 9:15
6
Add by
Configuration Properties>>C/C++>>Preporocessor>>Preprocessor
Definitions>> _CRT_SECURE_NO_WARNINGS
Sumurai8
20.4k11 gold badges66 silver badges100 bronze badges
answered Mar 17, 2014 at 9:37
BaluBalu
2,2571 gold badge18 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
nexusclarumnexusclarum
9711 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
kmcnameekmcnamee
5,1072 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(){
//...
}
answered Apr 14, 2019 at 16:22
CarlosioCarlosio
4094 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
30.1k10 gold badges100 silver badges143 bronze badges
answered Jan 24, 2019 at 8:39
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
rbentorbento
10.1k3 gold badges62 silver badges61 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
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 [101464 просмотра]
К этой статье пока нет комментариев, Ваш будет первым
- 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
-
Moved by
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 SupportPlease 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
-
Marked as answer by
When compiling C++ code, the compiler may produce warnings about unsafe or deprecated functions being used, such as strcpy or scanf. One way to suppress these warnings is to define the macro _CRT_SECURE_NO_WARNINGS. This macro tells the compiler to skip checking for security warnings related to functions that have been marked as deprecated or unsafe.
Method 1: Compiler Command Line
To use _CRT_SECURE_NO_WARNINGS
with the «Compiler Command Line» in C++, you need to follow these steps:
- Open your project in Visual Studio.
- Right-click on your project in the Solution Explorer and select «Properties».
- In the left-hand pane, select «Configuration Properties» > «C/C++» > «Command Line».
- In the «Additional Options» field, add the following command-line option:
/D_CRT_SECURE_NO_WARNINGS
. - Click «OK» to save the changes.
Here is an example code snippet that demonstrates the use of _CRT_SECURE_NO_WARNINGS
:
#define _CRT_SECURE_NO_WARNINGS // Disable secure warnings
#include
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str); // Warning: This function is not secure
printf("You entered: %s\n", str);
return 0;
}
In this example, _CRT_SECURE_NO_WARNINGS
is used to disable secure warnings when using the scanf()
function. Without this directive, the compiler would issue a warning about the potential for a buffer overflow when using scanf()
.
Method 2: Project Properties
To use _CRT_SECURE_NO_WARNINGS
in C++, follow these steps:
- Open your Visual Studio project.
- Right-click on the project name in the Solution Explorer and select «Properties».
- In the left-hand menu, select «Configuration Properties» -> «C/C++» -> «Preprocessor».
- In the «Preprocessor Definitions» field, add
_CRT_SECURE_NO_WARNINGS
. - Click «Apply» and then «OK» to save the changes.
Here is an example of how to use _CRT_SECURE_NO_WARNINGS
in your code:
#define _CRT_SECURE_NO_WARNINGS
#include
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
In this example, _CRT_SECURE_NO_WARNINGS
is defined before including the stdio.h
header file. This allows the use of the scanf
function without generating a warning.
Another example:
#define _CRT_SECURE_NO_WARNINGS
#include
int main() {
char name[20];
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!\n";
return 0;
}
In this example, _CRT_SECURE_NO_WARNINGS
is defined before including the iostream
header file. This allows the use of the std::cin
function without generating a warning.
Note that using _CRT_SECURE_NO_WARNINGS
disables some security checks, so use it with caution and only when necessary.
Method 3: pragma GCC diagnostic ignored
To use _CRT_SECURE_NO_WARNINGS
with pragma GCC diagnostic ignored
, you can follow these steps:
-
Add the following line at the top of your C++ file:
#pragma GCC diagnostic ignored "-Wformat-security"
This will suppress warnings related to format string vulnerabilities.
-
Replace any calls to
sprintf
orstrcpy
with their safer equivalents,snprintf
andstrncpy
. For example:// Before: sprintf(buffer, "%s", input); // After: snprintf(buffer, sizeof(buffer), "%s", input);
This will prevent buffer overflows and other security vulnerabilities.
-
Compile your code with the
-std=c++11
flag to enable the use ofsnprintf
andstrncpy
.g++ -std=c++11 myfile.cpp
This will ensure that your code is compiled with the latest C++ standard, which includes these safer functions.
Here is an example of how to use _CRT_SECURE_NO_WARNINGS
with pragma GCC diagnostic ignored
:
#include
#pragma GCC diagnostic ignored "-Wformat-security"
int main() {
char input[100];
char buffer[100];
printf("Enter a string: ");
scanf("%s", input);
snprintf(buffer, sizeof(buffer), "%s", input);
printf("You entered: %s\n", buffer);
return 0;
}
In this example, we use pragma GCC diagnostic ignored
to suppress warnings related to format string vulnerabilities. We also use snprintf
to safely copy the input string into a buffer, preventing buffer overflows. Finally, we compile the code with the -std=c++11
flag to enable the use of snprintf
.
Note that while this approach can help prevent security vulnerabilities in your code, it is still important to follow best practices for secure coding, such as input validation and proper memory management.