strcpy() error in Visual studio 2012

2020-05-29 00:29发布

so I have this code:

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

...

char* b = new char [10];
strcpy(b, "1234567890");

error: microsoft visual studio 11.0\vc\include\string.h(110) : see declaration of 'strcpy'

How do I fix it?

7条回答
我想做一个坏孩纸
2楼-- · 2020-05-29 00:29

There's an explanation and solution for this on MSDN:

The function strcpy is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow.

Consequently, as it suggests in the error description, you can use strcpy_s instead of strcpy:

strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );

and:

To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

http://social.msdn.microsoft.com/Forums/da-DK/vcgeneral/thread/c7489eef-b391-4faa-bf77-b824e9e8f7d2

查看更多
Fickle 薄情
3楼-- · 2020-05-29 00:43

Add this line top of the header

#pragma warning(disable : 4996)
查看更多
该账号已被封号
4楼-- · 2020-05-29 00:46

The message you are getting is advice from MS that they recommend that you do not use the standard strcpy function. Their motivation in this is that it is easy to misuse in bad ways (and the compiler generally can't detect and warn you about such misuse). In your post, you are doing exactly that. You can get rid of the message by telling the compiler to not give you that advice. The serious error in your code would remain, however.

You are creating a buffer with room for 10 chars. You are then stuffing 11 chars into it. (Remember the terminating '\0'?) You have taken a box with exactly enough room for 10 eggs and tried to jam 11 eggs into it. What does that get you? Not doing this is your responsibility and the compiler will generally not detect such things.

You have tagged this C++ and included string. I do not know your motivation for using strcpy, but if you use std::string instead of C style strings, you will get boxes that expand to accommodate what you stuff in them.

查看更多
冷血范
5楼-- · 2020-05-29 00:47

I had to use strcpy_s and it worked.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

struct student
{
    char name[30];
    int age;
};

int main()
{

    struct student s1;
    char myname[30] = "John";
    strcpy_s (s1.name, strlen(myname) + 1 ,myname );
    s1.age = 21;

    cout << " Name: " << s1.name << " age: " << s1.age << endl;
    return 0;
}
查看更多
放我归山
6楼-- · 2020-05-29 00:47

If you are getting an error saying something about deprecated functions, try doing #define _CRT_SECURE_NO_WARNINGS or #define _CRT_SECURE_NO_DEPRECATE. These should fix it. You can also use Microsoft's "secure" functions, if you want.

查看更多
▲ chillily
7楼-- · 2020-05-29 00:47

For my problem, I removed the #include <glui.h> statement and it ran without a problem.

查看更多
登录 后发表回答