Ошибка c4996 c strncpy

VaMpIr_DEX

2 / 2 / 3

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

Сообщений: 95

1

27.05.2014, 21:01. Показов 69806. Ответов 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



strncpy has a few dangerous quirks.

First, it zeros the target buffer past the end of the copy, which can be surprising.

Second, if there is not enough room in the target buffer, it does not null terminate the target buffer.

Third, if it truncates, it ‘mostly works’. Which discourages error handling (truncated strings are often worse than useless, but do not appear to be worse than useless at first glance).

strncpy_s requires an input length (or explicit truncation request), and errors if there is not enough room to null terminate (writing just a zero length string in the output). The input length is sometimes inefficient to provide (and not required for some of its changes), but it does guarantee a null terminated output buffer (so long as it isn’t a nullptr, or zero length) even in error conditions. I am unsure if it zeros past the end of the copied string or not.

This behavior prevents or mitigates some common fenceposting errors in string code.

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.

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

Hi!

Today I generated a glad.c file and includes for C++ and OpenGL 4.4 using your webservice.

When I tried to include it in my C++ Project (#include as well as adding the glad.c file to my project) and building that, I got the following two errors:

e:filesopenglglad.c(173): 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.

c:program files (x86)windows kits10include10.0.16299.0ucrtstring.h(343): note: see declaration of 'strncpy'

I tried reinstalling this exact windows kit but that didn’t help.

Is there any way I can solve this problem? Or did i make a mistake when generating the files / integrating them into my project?

~ Incendor

  • Ошибка c4996 c getch
  • Ошибка c4716 должна возвращать значение
  • Ошибка c4703 используется потенциально неинициализированная локальная переменная указатель
  • Ошибка c4700 использована неинициализированная локальная переменная
  • Ошибка c4600 kyocera 6530