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,10815 gold badges49 silver badges74 bronze badges
asked Oct 25, 2010 at 6:21
Sudantha Sudantha
15.6k43 gold badges105 silver badges160 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,1711 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
526k130 gold badges930 silver badges1208 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_WARNINGSprior to including CRT headers and this will make the warning go away.
answered Oct 25, 2010 at 6:26
sharptoothsharptooth
167k100 gold badges510 silver badges969 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 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 ).
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
84.6k12 gold badges139 silver badges236 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.4k19 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,6841 gold badge16 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
7791 gold badge7 silver badges11 bronze badges
|
VaMpIr_DEX 2 / 2 / 3 Регистрация: 24.03.2014 Сообщений: 95 |
||||
|
1 |
||||
|
27.05.2014, 21:01. Показов 69501. Ответов 7 Метки нет (Все метки)
Подскажите пожалуйста что за ошибка, и как ее исправить Ошибка 1 error 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. f:коледжvi-семестрнавчальна практикалаба_7лаба_7исходный код.cpp 37 1 Лаба_7
0 |
|
Почетный модератор 16842 / 6720 / 880 Регистрация: 12.06.2012 Сообщений: 19,967 |
|
|
27.05.2014, 21:05 |
2 |
|
Решение
1 |
|
2 / 2 / 3 Регистрация: 24.03.2014 Сообщений: 95 |
|
|
27.05.2014, 22:54 [ТС] |
3 |
|
Очень благодарен..) Добавлено через 1 час 41 минуту
0 |
|
2 / 2 / 0 Регистрация: 24.01.2016 Сообщений: 3 |
|
|
24.01.2016, 15:32 |
4 |
|
В свойствах проекта: Тогда ошибка станет обратно warning’ом, как в предыдущих версиях студии, и можно будет это игнорить.
2 |
|
GbaLog- |
|
24.01.2016, 16:20
|
|
Не по теме: aaalienx, Вовремя вы ответили.
0 |
|
aaalienx |
|
24.01.2016, 16:35
|
|
Не по теме: Какая разница? Я сам только что зашел на форум с этой ошибкой, значит, и кто-то другой может зайти. И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.
0 |
|
Почетный модератор 16842 / 6720 / 880 Регистрация: 12.06.2012 Сообщений: 19,967 |
|
|
24.01.2016, 19:16 |
7 |
|
И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный. Да неужели? Переходим по ссылке, которую я дал в этой теме — Копирование строк — error C4996: ‘strcpy’: This function or variable may be unsafe. Видим вариант с использованием strcpy_s. Если это нас не устраивает, то в этой теме есть еще одна ссылка — Выдает ошибку: error C4996: ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead, переходим по ней. Видим вариант с _CRT_SECURE_NO_WARNINGS. Если он нас не устраивает — смотрим следующее сообщение, где есть ссылка на предложенное вами решение https://www.cyberforum.ru/post5488517.html. Итого — за пару минут можно увидеть несколько возможных вариантов. Так что вы ошибаетесь, решение с конфигурацией настроек проекта в студии также присутствует.
0 |
|
2 / 2 / 0 Регистрация: 24.01.2016 Сообщений: 3 |
|
|
24.01.2016, 21:26 |
8 |
|
Сорри, ошибся, такой ответ правда есть. Я с какого-то уровня ссылок перестаю смотреть, возвращаюсь в гугл.
0 |
- Remove From My Forums
-
Question
-
// ptrstr.cpp -- using pointers to strings #include <iostream> #include <cstring> // declare strlen(), strcpy() int main() { using namespace std; char animal[20] = "bear"; // animal holds bear const char * bird = "wren"; // bird holds address of string char * ps; // uninitialized cout << animal << " and "; // display bear cout << bird << "n"; // display wren // cout << ps << "n"; //may display garbage, may cause a crash cout << "Enter a kind of animal: "; cin >> animal; // ok if input < 20 chars // cin >> ps; Too horrible a blunder to try; ps doesn't // point to allocated space ps = animal; // set ps to point to string cout << ps << "!n"; // ok, same as using animal cout << "Before using strcpy():n"; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; ps = new char[strlen(animal) + 1]; // get new storage strcpy_s(ps, animal); // copy string to new storage cout << "After using strcpy():n"; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; delete [] ps; cin.get(); cin.get(); return 0; }How to fix this : Error 1 error C4996: ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
I tried using strcpy_s but the following appeared:
Error 1 error C2660: ‘strcpy_s’ : function does not take 2 arguments c:usersalexandrosdocumentsvisual studio 2013projectslisting 4_20listing 4_20ptrstr.cpp 27 1 Listing 4_20
2 IntelliSense: no instance of overloaded function «strcpy_s» matches the argument list
argument types are: (char *, char [20]) c:UsersAlexandrosDocumentsVisual Studio 2013ProjectsListing 4_20Listing 4_20ptrstr.cpp 28 5 Listing 4_20Using VS2013 ultimate
-
Edited by
Tuesday, August 11, 2015 12:03 PM
-
Edited by
Answers
-
ps = new char[strlen(animal) + 1]; // get new storage strcpy_s(ps, sizeof(animal), animal); // copy string to new storag
You allocate strlen(animal) of space for the ps variable, and then in the next line of code, lie to the strcpy_s function and state that you allocated sizeof(animal) number of characters.
-
Edited by
Brian Muth
Tuesday, August 11, 2015 7:09 PM -
Marked as answer by
Shu 2017
Monday, August 24, 2015 6:00 AM
-
Edited by
-
Hi ClassicalGuitar,
If you can guarantee that the destination string has enough space to hold the source string including its null-terminator, just use strcpy() and ignore the compiling warning; if the compiling warning is carking, suppress it with
#define _CRT_SECURE_NO_WARNINGS
or
#pragma warning(disable : 4996)You may also use
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
to let the compiler automatically replaces strcpy() with strcpy_s() for you. See at
https://msdn.microsoft.com/en-us/library/ms175759.aspxFrom the MSDN document about strcpy() and strcpy_s(), the main difference between both is that, if the destination space is not enough, while strcpy() proceeds in silence, strcpy_s() calls default Invalid Parameter Handler Routine to consciously crash the
program and make you be awared of it with a report; see at
https://msdn.microsoft.com/en-us/library/ksazx244.aspx.You may overload the Invalid Parameter Handler Routine with your own function that not terminating the execution; in the case, strcpy_s() returns error; you are required to handle the program flow when the error happens.
If the destination and source strings overlap, the behaviors of strcpy() and strcpy_s() are undefined.
-
Marked as answer by
Shu 2017
Monday, August 24, 2015 6:00 AM
-
Marked as answer by
-
Reply both to Igor Tandetnik and kwick:
Read documentation for warning C4996
In C++, the easiest way to do that is to use Secure Template Overloads, which in many cases will eliminate deprecation warnings by replacing calls to deprecated functions
with calls to the new secure versions of those functions. For example, consider this deprecated call to
strcpy:char szBuf[10]; strcpy(szBuf, "test"); // warning: deprecated
Defining _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES as 1 eliminates the warning by changing the
strcpy call to strcpy_s, which prevents buffer overruns. For more information, see
Secure Template Overloads.The template overloads provide additional choices. Defining _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES to 1 enables template overloads of standard CRT functions that call the more secure variants automatically. If
_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES is 1, then no changes to the code are necessary. Behind the scenes, the call to
strcpy will be changed to a call to strcpy_s with the size argument supplied automatically.It is better for me to use a #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
Now code becomes:
// ptrstr.cpp -- using pointers to strings #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include <iostream> #include <cstring> // declare strlen(), strcpy() int main() { using namespace std; char animal[20] = "bear"; // animal holds bear const char * bird = "wren"; // bird holds address of string char * ps; // uninitialized cout << animal << " and "; // display bear cout << bird << "n"; // display wren // cout << ps << "n"; //may display garbage, may cause a crash cout << "Enter a kind of animal: "; cin >> animal; // ok if input < 20 chars // cin >> ps; Too horrible a blunder to try; ps doesn't // point to allocated space ps = animal; // set ps to point to string cout << ps << "!n"; // ok, same as using animal cout << "Before using strcpy():n"; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; ps = new char[strlen(animal) + 1]; // get new storage strcpy(ps, animal); // copy string to new storage cout << "After using strcpy():n"; cout << animal << " at " << (int *) animal << endl; cout << ps << " at " << (int *) ps << endl; delete [] ps; cin.get(); cin.get(); return 0; }and compiles and run without errors.
This issue is solved!
-
Marked as answer by
ClassicalGuitar
Friday, August 28, 2015 5:27 PM
-
Marked as answer by
In general, to compile C code you need a conforming C compiler. Visual Studio is a non-conforming C++ compiler.
You get the warning because Visual Studio is bad. See this.
C4996 appears whenever you use a function that Microsoft regards as obsolete. Apparently, Microsoft has decided that they should dictate the future of the C language, rather than the ISO C working group. Thus you get false warnings for perfectly fine code. The compiler is the problem.
There is nothing wrong with the strcpy() function, that’s a myth. This function has existed for some 30-40 years and every little bit of it is properly documented. So what the function does and what it does not should not come as a surprise, even to beginner C programmers.
What strcpy does and does not:
- It copies a null-terminated string into another memory location.
- It does not take any responsibility for error handling.
- It does not fix bugs in the caller application.
- It does not take any responsibility for educating C programmers.
Because of the last remark above, you must know the following before calling strcpy:
- If you pass a string of unknown length to strcpy, without checking its length in advance, you have a bug in the caller application.
- If you pass some chunk of data which does not end with
, you have a bug in the caller application. - If you pass two pointers to strcpy(), which point at memory locations that overlap, you invoke undefined behavior. Meaning you have a bug in the caller application.
For example, in the code you posted, you never initialized the arrays, so your program will likely crash and burn. That bug isn’t in the slightest related to the strcpy() function and will not be solved by swapping out strcpy() for something else.
Я получаю это предупреждение, но все функции работают нормально.
что это значит?
'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.
Ответ 1
Эта функция (strcpy) считается небезопасной из-за того, что проверка границ отсутствует и может привести к переполнению буфера. (На самом деле strcpy является позорным для переполнения эксплойтов, и все программисты его избегают — или, по крайней мере, должны его избегать). Совет должен использовать безопасную функцию, которая учитывает размер буфера назначения, чтобы избежать переполнения. Вы также можете использовать strncpy (НО с осторожностью!). Нет проблем с вашим кодом, т.е. Функции будут запускаться, как вы говорите, но попробуйте указать в качестве входного буфера, который больше, чем буфер назначения. Функция переполнит буфер назначения. Проверьте это также текст ссылки
Ответ 2
В то время как strcpy является общей строковой функцией, у нее есть история, которая является источником многих ошибок и явлений безопасности в программном обеспечении (из-за простоты переполнения буфера).
Microsoft, стремясь продвигать безопасное кодирование на C и С++, предоставила набор функций замены для опасных строковых методов. Как правило, у них есть оригинальное имя, перенесенное с помощью _s. Следовательно, защищенная версия strcpy от Microsoft — strcpy_s, как рекомендовано в предупреждении. Обратите внимание на эту особенность Microsoft, она не вездесущая.
У вас есть несколько вариантов.
- DEFINE _CRT_SECURE_NO_WARNINGS, если вы не хотите заботиться об этом, оставляя возможность проблем с безопасностью в вашем программном обеспечении.
- Замените свои строковые функции на безопасные, оставляя программное обеспечение менее портативным как следствие
- Оберните защищенные строковые функции и повсеместно используйте обертки, обеспечивая повышенную безопасность на платформах Windows и возвращайтесь к традиционным версиям на других платформах. Функции обертки могут выполняться с помощью MACRO или скомпилированных функций.
Я обычно делаю # 3.
Ответ 3
Поскольку вы программируете С++, правильным решением является запрет строк char* C-style из вашего кода, где это возможно, и заменить их на std::string (или другой подходящий тип строки).
Не используйте такие функции, как strcpy или strcpy_s или strncpy. Используйте конструктор копирования или оператор присваивания класса string. Или, если вам действительно нужно копировать буферы, используйте std::copy.
Ответ 4
Так как VС++ 8 strcpy() и огромный набор других функций считаются небезопасными, поскольку они не имеют проверки границ и могут приводят к переполнению буфера при неправильном использовании.
У вас есть два варианта:
- если вы не уверены — сделайте то, что говорит VС++, и используйте «безопасные» функции. Они вызовут обработчик ошибок, который завершит вашу программу, если что-то пойдет не так.
- Если вы знаете, что делаете, вы знаете, что никакого переполнения никогда не произойдет, и все краевые случаи обрабатываются вашим кодом — определите
_CRT_SECURE_NO_WARNINGSдо включения заголовков CRT, и это заставит предупреждение уйти.
Ответ 5
Это предупреждение в основном информирует вас о том, что strcpy устарел, поскольку копирование строки до может легко привести к неприятным проблемам (переполнение буфера). Причина, по которой strcpy все еще существует и работает, заключается в том, что она является частью стандартного наследия библиотеки, но вам действительно стоит использовать функции str * _s или strn * (которые не только полагаются на поиск завершающего ).
Так как переполнения буфера связаны не только с проблемами безопасности, но и с ошибками, которые относительно сложно отслеживать и исправлять, используя простые функции ванильной строки *, не только нахмуриться, но и может привести к тому, что люди откажутся от вашего кода как неотъемлемо небезопасный.
Подробнее:
http://www.safercode.com/blog/2008/11/04/unsafe-functions-in-c-and-their-safer-replacements-strings-part-i.html
Ответ 6
Существует актуальный способ избежать этого предупреждения, по-прежнему использовать strcpy и быть в безопасности:
Вы можете включить безопасные перегрузки шаблонов. Они будут (если возможно) вывести длины буферов, используемых для их захвата с помощью шаблонных перегрузок. Для меня загадка, почему это не включено по умолчанию в Visual С++.
Ответ 7
#pragma warning(disable: 4996)
используйте код выше в первой строке вашего кода.
Ответ 8
Если вы посмотрели на плюсы и минусы использования метода пуриста С++, а не на беспокойство, потому что вы знаете, что ваши строки будут завершены нулем, тогда вы также можете отключить предупреждение в msvc, что-то вроде:
#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 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
Ответ 9
использовать Защищенные перегрузки шаблонов или определить функции обертки работа для динамически распределенных буферов, поэтому эта попытка бесполезна.
Либо измените источник, чтобы использовать безопасную замену, либо просто проигнорируйте его.
если коды пишут самостоятельно, вам лучше изменить такие strcpy на strcpy_s и т.д.
если модули импортированы из надежных источников, вы можете игнорировать предупреждение.
игнорировать метод 1: область действия глобуса проекта: добавить _CRT_SECURE_NO_WARNINGS
игнорировать метод 2: игнорировать конкретный модуль: если только один или два из них, то вы можете просто предупредить об этом для этих модулей при их включении:
#pragma warning(push)
#pragma warning(disable: 4996)
#include <sapi.h> //legacy module
#include <sphelper.h> //legacy module
#pragma warning(pop)

Сообщение было отмечено VaMpIr_DEX как решение
