Strcpy c ошибка c4996

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's user avatar

Cole Tobin

9,20615 gold badges49 silver badges74 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

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 Rudolph's user avatar

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

sharptooth's user avatar

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's user avatar

Gabe

85k12 gold badges140 silver badges238 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.7k19 gold badges86 silver badges87 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

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

raidsan's user avatar

raidsanraidsan

7771 gold badge7 silver badges11 bronze badges

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's user avatar

Cole Tobin

9,20615 gold badges49 silver badges74 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

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 Rudolph's user avatar

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

sharptooth's user avatar

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's user avatar

Gabe

85k12 gold badges140 silver badges238 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.7k19 gold badges86 silver badges87 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

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

raidsan's user avatar

raidsanraidsan

7771 gold badge7 silver badges11 bronze badges

VaMpIr_DEX

2 / 2 / 3

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

Сообщений: 95

1

27.05.2014, 21:01. Показов 70484. Ответов 7

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


Студворк — интернет-сервис помощи студентам

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <cstring>
#include <fstream>
#include<string>
#include<iomanip>
 
using namespace std;
 
struct link
{
    int age;
    char firstname[10];
    char name[10];
 
    link *next;
 
};
 
class linklist
{
private: link *first;
 
public: linklist()
{
            first = NULL;
}
 
        void add(char * firstname, char* name, int _age);
        void dis();
        void input();
        void zapus(char * firstname, char* name, int _age);
};
void linklist::add(char * firstname, char* name, int _age)
{
    link *newlink = new link;
    newlink->age = _age;
    strcpy(newlink->firstname,firstname);
    strcpy(newlink->name, name);
 
    newlink->next = first;
    first = newlink;
    }
void linklist::dis()
{
    link *current = first;
    while (current)
    {
        cout << current->firstname << endl << current->name << endl<<current ->age;
        current = current->next;
 
    }
}
 
void linklist::input()
{
    char name[10];
    char firstname[10];
    int age;
    cout << "Enter firstname->";
    cin >> firstname;
    cout << "Enter name->";
    cin >> name;
        cout << "Enter age->";
    cin >> age;
    add(firstname, name, age);
    zapus(firstname, name, age);
 
 
}
void linklist::zapus(char * firstname, char* name, int age)
{
    ofstream fout;
 
    fout.open("text.txt", ios::app);
    fout << "\tName: " << name << "\t Firstname: " << firstname << endl
        << "\t age: " << age << endl;
    fout.close();
}
 
int main()
{
    linklist l1;
    l1.input();
}

Подскажите пожалуйста что за ошибка, и как ее исправить

Ошибка 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



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6721 / 880

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

Сообщений: 19,967

27.05.2014, 21:05

2

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

Решение



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

В свойствах проекта:
properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No.

Тогда ошибка станет обратно warning’ом, как в предыдущих версиях студии, и можно будет это игнорить.



2



GbaLog-

24.01.2016, 16:20

Не по теме:

aaalienx, Вовремя вы ответили. :D



0



aaalienx

24.01.2016, 16:35

Не по теме:

Какая разница? Я сам только что зашел на форум с этой ошибкой, значит, и кто-то другой может зайти. И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6721 / 880

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

Сообщений: 19,967

24.01.2016, 19:16

7

Цитата
Сообщение от aaalienx
Посмотреть сообщение

И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.

Да неужели? Переходим по ссылке, которую я дал в этой теме — Копирование строк — 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

  • I am beginner. and my coding is followed.

    The error message is «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.:

    What I need to do???

    #include <Turboc.h>
    #include <istream>
    using namespace std;

    class Person
    {
    protected:
        char *Name;
        int Age;

    public:
        Person(){
            Name = new char[1];
            Name[0] = NULL;
            Age = 0;
        }
        Person(const char *aName, int aAge){
            Name = new char[strlen(aName) + 1];
            strcpy(Name, aName);
            Age = aAge;
        }
        Person(const Person &Other){
            Name = new char[strlen(Other.Name) + 1];
            strcpy(Name, Other.Name);
            Age = Other.Age;
        }
        virtual ~Person(){
            delete[]Name;
        }
        void OutPerson(){
            printf(«NName:%s AAge:%d\n», Name, Age);
        }
        Person &operator=(const Person &Other){
            if (this != &Other){
                delete[]Name;
                Name = new char[strlen(Other.Name) + 1];
                strcpy(Name, Other.Name);
                Age = Other.Age;
            }
            return *this;
        }
    };

    void main()
    {
        Person Boy(«Kanggamchan», 22);
        Person Young(«Ealgimunduk», 25);
        Young = Boy;
        Young.OutPerson();
    }

Answers

  • If you still want to use the strcpy().
    please add: #pragma warning( disable: 4996 )


    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.

    • Proposed as answer by

      Friday, October 16, 2015 3:20 AM

    • Marked as answer by
      May Wang — MSFT
      Monday, October 19, 2015 2:13 AM

  • Or project properties/ C/C++ Command Line
    Add: /D _CRT_SECURE_NO_WARNINGS


    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.

    • Proposed as answer by
      May Wang — MSFT
      Friday, October 16, 2015 3:20 AM
    • Marked as answer by
      May Wang — MSFT
      Monday, October 19, 2015 2:13 AM

  • I am beginner. and my coding is followed.

    The error message is «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.:

    Some traditional functions from C and C++ which are still supported in the Standards
    can pose some security risks in applications which could potentially be exploited by
    hackers, if those functions are used incorrectly. So the compiler has implemented «safer»
    versions which will catch such incorrect usage at runtime and cause an error message.

    For learning purposes, especially if working from a textbook or course materials, you
    can still use the «non-secure» versions which are part of the C/C++ language Standards.
    As the message you got from the compiler suggests. you can put this:

    #define _CRT_SECURE_NO_WARNINGS

    at the start of your code before the #include statements. Or use the #pragma already
    suggested. See:

    Security Features in the CRT
    https://msdn.microsoft.com/en-us/library/8ef0s5kh.aspx

    — Wayne

    • Proposed as answer by
      May Wang — MSFT
      Friday, October 16, 2015 3:20 AM
    • Marked as answer by
      May Wang — MSFT
      Monday, October 19, 2015 2:13 AM

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's user avatar

Cole Tobin

9,02315 gold badges49 silver badges72 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

Sudantha Sudantha

15.3k42 gold badges104 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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

MontdidierMontdidier

1,1411 gold badge8 silver badges20 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 Rudolph's user avatar

Konrad RudolphKonrad Rudolph

520k128 gold badges926 silver badges1204 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

sharptooth's user avatar

sharptoothsharptooth

166k99 gold badges508 silver badges963 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's user avatar

Gabe

84.1k12 gold badges137 silver badges235 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.1k19 gold badges85 silver badges86 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

JoséJosé

1,6541 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

raidsan's user avatar

raidsanraidsan

7811 gold badge7 silver badges11 bronze badges

VaMpIr_DEX

2 / 2 / 3

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

Сообщений: 95

1

27.05.2014, 21:01. Показов 66458. Ответов 7

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


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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <cstring>
#include <fstream>
#include<string>
#include<iomanip>
 
using namespace std;
 
struct link
{
    int age;
    char firstname[10];
    char name[10];
 
    link *next;
 
};
 
class linklist
{
private: link *first;
 
public: linklist()
{
            first = NULL;
}
 
        void add(char * firstname, char* name, int _age);
        void dis();
        void input();
        void zapus(char * firstname, char* name, int _age);
};
void linklist::add(char * firstname, char* name, int _age)
{
    link *newlink = new link;
    newlink->age = _age;
    strcpy(newlink->firstname,firstname);
    strcpy(newlink->name, name);
 
    newlink->next = first;
    first = newlink;
    }
void linklist::dis()
{
    link *current = first;
    while (current)
    {
        cout << current->firstname << endl << current->name << endl<<current ->age;
        current = current->next;
 
    }
}
 
void linklist::input()
{
    char name[10];
    char firstname[10];
    int age;
    cout << "Enter firstname->";
    cin >> firstname;
    cout << "Enter name->";
    cin >> name;
        cout << "Enter age->";
    cin >> age;
    add(firstname, name, age);
    zapus(firstname, name, age);
 
 
}
void linklist::zapus(char * firstname, char* name, int age)
{
    ofstream fout;
 
    fout.open("text.txt", ios::app);
    fout << "tName: " << name << "t Firstname: " << firstname << endl
        << "t age: " << age << endl;
    fout.close();
}
 
int main()
{
    linklist l1;
    l1.input();
}

Подскажите пожалуйста что за ошибка, и как ее исправить

Ошибка 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

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

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

Сообщений: 19,967

27.05.2014, 21:05

2

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

Решение

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

В свойствах проекта:
properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No.

Тогда ошибка станет обратно warning’ом, как в предыдущих версиях студии, и можно будет это игнорить.

2

GbaLog-

24.01.2016, 16:20

Не по теме:

aaalienx, Вовремя вы ответили. :D

0

aaalienx

24.01.2016, 16:35

Не по теме:

Какая разница? Я сам только что зашел на форум с этой ошибкой, значит, и кто-то другой может зайти. И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.

0

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

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

Сообщений: 19,967

24.01.2016, 19:16

7

Цитата
Сообщение от aaalienx
Посмотреть сообщение

И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.

Да неужели? Переходим по ссылке, которую я дал в этой теме — Копирование строк — 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

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's user avatar

Cole Tobin

9,02315 gold badges49 silver badges72 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

Sudantha Sudantha

15.3k42 gold badges104 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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

MontdidierMontdidier

1,1411 gold badge8 silver badges20 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 Rudolph's user avatar

Konrad RudolphKonrad Rudolph

520k128 gold badges926 silver badges1204 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

sharptooth's user avatar

sharptoothsharptooth

166k99 gold badges508 silver badges963 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's user avatar

Gabe

84.1k12 gold badges137 silver badges235 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.1k19 gold badges85 silver badges86 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

JoséJosé

1,6541 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

raidsan's user avatar

raidsanraidsan

7811 gold badge7 silver badges11 bronze badges

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's user avatar

Cole Tobin

9,02315 gold badges49 silver badges72 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

Sudantha Sudantha

15.3k42 gold badges104 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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

MontdidierMontdidier

1,1411 gold badge8 silver badges20 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 Rudolph's user avatar

Konrad RudolphKonrad Rudolph

520k128 gold badges926 silver badges1204 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

sharptooth's user avatar

sharptoothsharptooth

166k99 gold badges508 silver badges963 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's user avatar

Gabe

84.1k12 gold badges137 silver badges235 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.1k19 gold badges85 silver badges86 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

JoséJosé

1,6541 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

raidsan's user avatar

raidsanraidsan

7811 gold badge7 silver badges11 bronze badges

  • 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_20

    Using VS2013 ultimate

    • Edited by

      Tuesday, August 11, 2015 12:03 PM

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
  • 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.aspx

    From 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
  • 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

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

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

Перейти к контенту

VaMpIr_DEX

2 / 2 / 3

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

Сообщений: 95

1

27.05.2014, 21:01. Показов 66442. Ответов 7

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


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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <cstring>
#include <fstream>
#include<string>
#include<iomanip>
 
using namespace std;
 
struct link
{
    int age;
    char firstname[10];
    char name[10];
 
    link *next;
 
};
 
class linklist
{
private: link *first;
 
public: linklist()
{
            first = NULL;
}
 
        void add(char * firstname, char* name, int _age);
        void dis();
        void input();
        void zapus(char * firstname, char* name, int _age);
};
void linklist::add(char * firstname, char* name, int _age)
{
    link *newlink = new link;
    newlink->age = _age;
    strcpy(newlink->firstname,firstname);
    strcpy(newlink->name, name);
 
    newlink->next = first;
    first = newlink;
    }
void linklist::dis()
{
    link *current = first;
    while (current)
    {
        cout << current->firstname << endl << current->name << endl<<current ->age;
        current = current->next;
 
    }
}
 
void linklist::input()
{
    char name[10];
    char firstname[10];
    int age;
    cout << "Enter firstname->";
    cin >> firstname;
    cout << "Enter name->";
    cin >> name;
        cout << "Enter age->";
    cin >> age;
    add(firstname, name, age);
    zapus(firstname, name, age);
 
 
}
void linklist::zapus(char * firstname, char* name, int age)
{
    ofstream fout;
 
    fout.open("text.txt", ios::app);
    fout << "tName: " << name << "t Firstname: " << firstname << endl
        << "t age: " << age << endl;
    fout.close();
}
 
int main()
{
    linklist l1;
    l1.input();
}

Подскажите пожалуйста что за ошибка, и как ее исправить

Ошибка 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

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

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

Сообщений: 19,967

27.05.2014, 21:05

2

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

Решение

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

В свойствах проекта:
properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No.

Тогда ошибка станет обратно warning’ом, как в предыдущих версиях студии, и можно будет это игнорить.

2

GbaLog-

24.01.2016, 16:20

Не по теме:

aaalienx, Вовремя вы ответили.

0

aaalienx

24.01.2016, 16:35

Не по теме:

Какая разница? Я сам только что зашел на форум с этой ошибкой, значит, и кто-то другой может зайти. И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.

0

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

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

Сообщений: 19,967

24.01.2016, 19:16

7

Цитата
Сообщение от aaalienx
Посмотреть сообщение

И во всех похожих темах нет этого ответа, а он, на мой взгляд, оптимальный.

Да неужели? Переходим по ссылке, которую я дал в этой теме — Копирование строк — 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

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's user avatar

Cole Tobin

9,01315 gold badges49 silver badges72 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

Sudantha Sudantha

15.3k42 gold badges104 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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

MontdidierMontdidier

1,1411 gold badge8 silver badges20 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 Rudolph's user avatar

Konrad RudolphKonrad Rudolph

520k127 gold badges925 silver badges1203 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

sharptooth's user avatar

sharptoothsharptooth

166k99 gold badges508 silver badges963 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's user avatar

Gabe

84.1k12 gold badges137 silver badges235 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.1k19 gold badges85 silver badges86 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

JoséJosé

1,6541 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

raidsan's user avatar

raidsanraidsan

7811 gold badge7 silver badges11 bronze badges

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's user avatar

Cole Tobin

9,01315 gold badges49 silver badges72 bronze badges

asked Oct 25, 2010 at 6:21

Sudantha 's user avatar

Sudantha Sudantha

15.3k42 gold badges104 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

Cratylus's user avatar

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.

  1. DEFINE _CRT_SECURE_NO_WARNINGS if you don’t want to care about it, leaving the possibility of the security issues in your software.
  2. Replace your string functions with the secure ones, leaving your software less portable as a consequence
  3. 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

Montdidier's user avatar

MontdidierMontdidier

1,1411 gold badge8 silver badges20 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 Rudolph's user avatar

Konrad RudolphKonrad Rudolph

520k127 gold badges925 silver badges1203 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

sharptooth's user avatar

sharptoothsharptooth

166k99 gold badges508 silver badges963 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's user avatar

Gabe

84.1k12 gold badges137 silver badges235 bronze badges

answered Oct 25, 2010 at 6:30

Vladski's user avatar

1

#pragma warning(disable: 4996)

use above code in the first line of your code.

Sateesh Pagolu's user avatar

answered Aug 29, 2015 at 10:24

Kool Wagh's user avatar

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's user avatar

Cezar

55.1k19 gold badges85 silver badges86 bronze badges

answered Jul 24, 2013 at 16:28

brett bazant's user avatar

#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é's user avatar

JoséJosé

1,6541 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

raidsan's user avatar

raidsanraidsan

7811 gold badge7 silver badges11 bronze badges

  • 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_20

    Using VS2013 ultimate

    • Edited by

      Tuesday, August 11, 2015 12:03 PM

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
  • 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.aspx

    From 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
  • 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

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

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

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

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

Only difference between projects is several different options in wizard.

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

SOLUTION 1 :

Add by

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

screenshot of the relevant config interface

SOLUTION 2 :

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

SOLUTION 3 :

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

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

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

SDL checks in vs2012 and later

SOLUTION 4 :

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

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

SOLUTION 5 :

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

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

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


Recommended Answers

Don’t worry, it’s not an error: it’s a VC++ warning. Ignore it (in this case). See notes in MSDN help page on this function (click strncpy then press F1).

Jump to Post

MS (and probably other compiler vendors) are revising the string function to ensure greater safety. With strcpy, strcat and their variations, it’s very easy to try to stuff more into a string array than it can hold. Therein lies the opening that many malware authors have exploited.

You can …

Jump to Post

All 5 Replies

Member Avatar

ArkM

14 Years Ago

Don’t worry, it’s not an error: it’s a VC++ warning. Ignore it (in this case). See notes in MSDN help page on this function (click strncpy then press F1).

Member Avatar

14 Years Ago

It means that strncpy is old and/or something better is around to use instead of it.

Member Avatar

vmanes

14 Years Ago

MS (and probably other compiler vendors) are revising the string function to ensure greater safety. With strcpy, strcat and their variations, it’s very easy to try to stuff more into a string array than it can hold. Therein lies the opening that many malware authors have exploited.

You can update your code to use the secure versions (they have an «_s» suffix and pass a parameter that is the size of the destination array), or continue with the old tried and true versions, adding the following to your code to suppress the warnings.
~~~~~~~~
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE

Use these #define’s to halt the many warnings given by
Visual C++ 2005/2008 for use of «unsafe» string functions.
Place them before your #include statements.

see the link below for a full list of the functions that have
secure variations available

http://msdn2.microsoft.com/en-us/library/ms235384(VS.80).aspx

Member Avatar

Salem

14 Years Ago

Of course the real answer would be to use another std::string which is totally safe, as opposed to some non-portable API which is only safe so long as the programmer knows what they’re doing.

Member Avatar


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

  • Forum
  • General C++ Programming
  • Strncpy Error

Strncpy Error

Im receiving a error C4996 and says it is unsafe to use «strncpy», how can I fix this?

If you are using Visual Studio you can #define _CRT_SECURE_NO_WARNINGS before your #include files.

Not recommended. It is using a bomb to swat a fly. And doesn’t fix the problems with the functions, you can still have buffer overruns.

OR

Use C11’s strncpy_s() function that was created to prevent buffer overruns.

See TheIdeasMan’s link for how to use.

At the design level, while the above answers tell you how to use strncpy safely, you might consider not using it at all. If you can, just use a C++ string type instead.

strncpy isn’t unsafe as it’s bounded by the buffer size of the input and/or the string length of the input.

Last edited on

That strncpy is unsafe and deprecated is Microsoft’s own opinion, it still part of C and C++ standard.
The suggested alternative strncpy_s is only supported on Visual Studio and C11.

IMHO people who like safety shouldn’t use C or C++ at all.

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Summertime saga ошибка
  • Stray ошибка при запуске
  • Summercamp exe ошибка приложения friday 13
  • Stray ошибка lowlevelfatalerror
  • Summer memories ошибка