I was seeing an old simple algorithm I had done a while ago. I did it using dev-c ++, but now I compiled it in visual studio and it doesn't work. Visual studio compiler says: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. (line 17)
In this easy project you will type a phrase, then you get the phrase translated in hex (each character).
So why dev-c++ doesn't tell me that? Did I make any mistakes? Or not... The code is ok? I want to understand that because it's not the first time i receive that error.
Code execution example:
Please insert a phrase: hello world! The string -hello world!- converted in hex is 68 65 6c 6c 6f 20 77 6f 72 6c 64 21
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string phrase;
char* chArray;
cout << "Pls insert a phrase:\t";
getline(cin, phrase);
chArray = new char[phrase.size() + 1];
strcpy(chArray, phrase.c_str()); //THE ERROR IS HERE!
cout << "The string -" << phrase << "- converted in hex is\n";
for (int i = 1; i < static_cast<int>(phrase.size() + 1); i++)
{
int ch = (int)chArray[i-1];
cout << setbase(16) << ch << " ";
if (i % 5 == 0)
cout << "\n";
}
return 0;
}
You get this warning when you use any of the "unsafe" byte copying functions. It's mostly specific to MSVC.
To fix it, use strcpy_s
which requires you to also pass a maximum number of bytes to copy (which should be the size of the destination buffer). This prevents buffer overflows.
strcpy_s(chArray, phrase.size()+1, phrase.c_str());
That said, it's easier to use std::string
for all this in C++
Collected from the Internet
Please contact javaer1[email protected] to delete if infringement.
Comments