[c++] strcpy() error in Visual studio 2012

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?

This question is related to c++ visual-studio-2012

The answer is


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.


Add this line top of the header

#pragma warning(disable : 4996)

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;
}

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


A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.


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.