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:
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
23.5k7 gold badges29 silver badges53 bronze badges
asked Dec 7, 2013 at 23:39
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
NikolaiNikolai
3,0633 gold badges24 silver badges34 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
Nitay DereiNitay Derei
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 TsengPeter Tseng
13.6k4 gold badges67 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
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.Adam G.
811 silver badge10 bronze badges
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:
- 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
- Or statement
#pragma warning(disable:4996)
- 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:
I am getting this warning but all functions working properly .
what does this really means?
'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.
Cole Tobin
9,20515 gold badges49 silver badges74 bronze badges
asked Oct 25, 2010 at 6:21
Sudantha Sudantha
15.7k44 gold badges105 silver badges161 bronze badges
14
This function (strcpy) is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow. (Actually strcpy is infamous for overflow exploits and all programmers avoid it-or at least should avoid it). The advice is to use a safe function which takes into account the size of the destination buffer to avoid overflow. You could also use strncpy (BUT with caution!). There is no problem with your code, i.e. the functions will run as you say but try giving as input a buffer that is larger than the destination buffer. The function will overflow the destination buffer. Check this also link text
answered Oct 25, 2010 at 6:22
16
While strcpy is a common string function, it has a history of being the source of many bugs and security holes in software (due to the ease of buffer overflows).
Microsoft, in an effort to promote safer coding in C and C++ has provided a suite of replacement functions for the dangerous string methods. Typically they have the original name postpended with _s. Hence the Microsoft secure version of strcpy is strcpy_s as recommended in the warning. Note this a Microsoft specific feature, it’s not ubiquitious.
You’ve got a few options.
- DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
- Replace your string functions with the secure ones, leaving your software less portable as a consequence
- Wrap the secure string functions and use the wrappers everywhere, providing enhanced security on Windows platforms, and falling back to the traditional versions on other platforms. The wrapper functions could be via a MACRO or compiled functions.
I typically do #3.
answered Oct 25, 2010 at 6:30
MontdidierMontdidier
1,1911 gold badge8 silver badges21 bronze badges
4
Since you’re programming C++, the correct solution is to ban C-style char*
strings from your code where possible, and replace them by std::string
(or another appropriate string type).
Do not use functions such as strcpy
or strcpy_s
or strncpy
. Use the copy constructor or assignment operator of the string
class. Or if you really need to copy buffers, use std::copy
.
answered Oct 25, 2010 at 6:34
Konrad RudolphKonrad Rudolph
531k133 gold badges939 silver badges1214 bronze badges
0
Since VC++ 8 strcpy()
and a huge set of other functions are considered to be unsafe since they don’t have bounds checking and can lead to a buffer overrun if misused.
You have two options:
- if you’re unsure — do what VC++ says and use «safe» functions. They will trigger an error handler that will terminate your program if something goes wrong.
- if you know what you’re doing — you know that no overrun will ever occur and all edge cases are handled by your code — define
_CRT_SECURE_NO_WARNINGS
prior to including CRT headers and this will make the warning go away.
answered Oct 25, 2010 at 6:26
sharptoothsharptooth
168k101 gold badges513 silver badges979 bronze badges
1
There is actualy a way to avoid this warning, still use strcpy, and be safe:
You can enable the secure template overloads. They will (if possible) deduce the lengths of the buffers used by capturing them with templated overloads. It’s a mystery to me why this is not enabled by default in Visual C++.
answered Oct 25, 2010 at 6:37
That warning is basically informing you that strcpy is deprecated, because copying a string until \0
can easily lead to nasty problems (buffer overruns). The reason strcpy is still there and works is that it is part of the standard library legacy, but you should really consider using str*_s or strn* functions (which don’t exclusively rely on finding the terminating \0
).
Since buffer overruns are linked not only to security problems, but also to bugs which are relatively difficult to trace and fix, using plain vanilla str* functions is not only generally frowned upon, but can lead to people rejecting your code as inherently unsafe.
More details:
http://www.safercode.com/blog/2008/11/04/unsafe-functions-in-c-and-their-safer-replacements-strings-part-i.html
Gabe
85k12 gold badges140 silver badges238 bronze badges
answered Oct 25, 2010 at 6:30
1
#pragma warning(disable: 4996)
use above code in the first line of your code.
answered Aug 29, 2015 at 10:24
Kool WaghKool Wagh
591 silver badge4 bronze badges
1
If you have looked at the pros and cons of using C++ purist technique vs. not worrying because you ‘know’ your strings will be zero terminated, then you can also disable the warning in msvc, this sort of thing:
#ifdef _MSC_VER
// 4231: nonstandard extension used : 'extern' before template explicit instantiation
// 4250: dominance
// 4251: member needs to have dll-interface
// 4275: base needs to have dll-interface
// 4660: explicitly instantiating a class that's already implicitly instantiated
// 4661: no suitable definition provided for explicit template instantiation request
// 4786: identifer was truncated in debug information
// 4355: 'this' : used in base member initializer list
// 4910: '__declspec(dllexport)' and 'extern' are incompatible on an explicit instantiation
# pragma warning(disable: 4231 4250 4251 4275 4660 4661 4786 4355 4910)
#endif
Cezar
55.7k19 gold badges86 silver badges87 bronze badges
answered Jul 24, 2013 at 16:28
#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
at the top of the file worked for me
(based on other SO user’s answer… but I couldn’t find to ref him/her)
answered Apr 21, 2021 at 3:15
JoséJosé
1,7841 gold badge17 silver badges21 bronze badges
use Secure Template Overloads or define wrapper functions not work for dynamically allocated buffers, so this attempt is futile.
Either modify source to use secure replacement, or just ignore it.
if the codes are writing by yourself, you had better change such strcpy to strcpy_s etc.
if the modules are imported from trusted soures, you may choose to ignore the warning.
ignore method 1: project globle scope: add _CRT_SECURE_NO_WARNINGS
ignore method 2: ignore particular module: if only one or two of them, then you could simplely forbit warning for these modules when include them:
#pragma warning(push)
#pragma warning(disable: 4996)
#include <sapi.h> //legacy module
#include <sphelper.h> //legacy module
#pragma warning(pop)
answered Jun 14, 2013 at 5:11
raidsanraidsan
7771 gold badge7 silver badges11 bronze badges
Gusev 0 / 0 / 0 Регистрация: 04.12.2014 Сообщений: 10 |
||||
1 |
||||
29.01.2015, 21:33. Показов 34330. Ответов 15 Метки нет (Все метки)
Здравствуйте, у меня показывать ошибку C4996: ‘fopen’. помогите исправить.
0 |
zss Модератор 13407 / 10517 / 6283 Регистрация: 18.12.2011 Сообщений: 28,074 |
||||
29.01.2015, 21:39 |
2 |
|||
2 |
7538 / 6399 / 2918 Регистрация: 14.04.2014 Сообщений: 27,865 |
|
29.01.2015, 21:41 |
3 |
<cstdio> подключи.
0 |
1500 / 1146 / 165 Регистрация: 05.12.2011 Сообщений: 2,279 |
|
29.01.2015, 21:41 |
4 |
вообще нужно полный текст ошибок/предупреждений приводить.
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 минуту
0 |
1500 / 1146 / 165 Регистрация: 05.12.2011 Сообщений: 2,279 |
|
29.01.2015, 21:43 |
6 |
наверно потому, что оно принимает три: _CRT_SECURE_NO_WARNINGS — вот это вы где задефайнили? надо чтобы перед инклудом это было.
0 |
7538 / 6399 / 2918 Регистрация: 14.04.2014 Сообщений: 27,865 |
|
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
0 |
DU 1500 / 1146 / 165 Регистрация: 05.12.2011 Сообщений: 2,279 |
||||
29.01.2015, 21:49 |
9 |
|||
так? если так и все равно проблемы — тогда хз.
1 |
0 / 0 / 0 Регистрация: 04.12.2014 Сообщений: 10 |
|
29.01.2015, 22:06 [ТС] |
10 |
nmcf, а как это сделать? у меня английская версия, плохо понимаю. Добавлено через 15 минут
0 |
7538 / 6399 / 2918 Регистрация: 14.04.2014 Сообщений: 27,865 |
|
29.01.2015, 22:26 |
11 |
В разделе C/C++ — обрабатывать предупреждения как ошибки — Нет.
0 |
1500 / 1146 / 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 |
1500 / 1146 / 165 Регистрация: 05.12.2011 Сообщений: 2,279 |
|
29.01.2015, 23:01 |
14 |
Решение В свойствах:
3 |
0 / 0 / 0 Регистрация: 04.12.2014 Сообщений: 10 |
|
29.01.2015, 23:19 [ТС] |
15 |
а теперь выводит вот это http://rghost.ru/8J7k4jhT5 Добавлено через 3 минуты
0 |
1500 / 1146 / 165 Регистрация: 05.12.2011 Сообщений: 2,279 |
|
30.01.2015, 00:03 |
16 |
это у вас рантайм ошибка. глюк в коде, а не в студии.
0 |
При компиляции такого кода
#include <iostream>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
int main() {
const int maxSymbols = 15;
char* word1 = new char[maxSymbols];
char* word2 = new char[maxSymbols];
cout << "Enter five words : ";
cin >> word1;
cin >> word2;
cout << endl << strcat(word1, word2);
}
Появляется ошибка C4996 ‘strcat’: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
После появления этой ошибки в начале дописал #define _CRT_SECURE_NO_WARNINGS
но это ничего не изменило.
Помогите пожалуйста.
-
Вопрос задан
-
1810 просмотров
Пригласить эксперта
Попробуйте ввести более 10 символов в word1 и word2 и у вас программа непредсказуемо упадёт.
Если использовать strcat_s, то она проверит граничные условия и выдаст ошибку, если они не выполняются.
Для использования strcat_s нужно немного переписать программу — обработать ошибку и знать размер первого буфера.
Данил Васькевич, прикинь, блин! Или как компилятор советует вместо strcat использовать strcat_s, или указать дифайн _CRT_SECURE_NO_WARNINGS (в Visual Studio его можно указать в свойствах проекта, глобально). Ну лучше всё же не пользоваться небезопасными функциями, а перейти на функции с суфиксом _s везде где только возможно, а не только в этом случае. Дифайн _CRT_SECURE_NO_WARNINGS это плохое решение, подходит на «только сейчас и для старого кода чтобы поддерживался», а новый код не надо на него расчитывать, надо пользоваться безопасными функциями.
-
Показать ещё
Загружается…
22 сент. 2023, в 11:59
3500 руб./за проект
22 сент. 2023, в 11:34
2500 руб./за проект
22 сент. 2023, в 11:24
30000 руб./за проект