c++ - 如何修复编译错误 "This function or variable may be unsafe"(strcpy)

标签 c++ string pointers char

我看到了一个我之前做过的简单算法。我是用dev-c++做的,现在用visual studio编译了,还是不行。 Visual Studio 编译器说:“strcpy”:此函数或变量可能不安全。考虑改用 strcpy_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。 (第 17 行)

在这个简单的项目中,您将输入一个短语,然后您会得到翻译成十六进制(每个字符)的短语。

那么为什么 dev-c++ 不告诉我呢?我犯了什么错误吗?或者不是...代码可以吗?我想了解这一点,因为这不是我第一次收到该错误。

代码执行示例:

请插入一个短语:hello world! 字符串 -hello world!- 以十六进制转换为 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;
}

最佳答案

当您使用任何“不安全”的字节复制函数时,您会收到此警告。它主要特定于 MSVC。

要修复它,请使用 strcpy_s这要求您还传递要复制的最大字节数(应该是目标缓冲区的大小)。这可以防止缓冲区溢出。

strcpy_s(chArray, phrase.size()+1, phrase.c_str());

也就是说,在 C++ 中使用 std::string 更容易

关于c++ - 如何修复编译错误 "This function or variable may be unsafe"(strcpy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101085/

相关文章:

c++ - C或C++语言中的数组实际上是指针吗

c++ - 使用 decltype() 的 SFINAE 在 Visual Studio 2012 上忽略 "private"

c++ - 为 arm-none-eabi-gcc 交叉编译库

python - 不区分大小写的列表排序,不小写结果?

arrays - 在 C 中初始化了一个指针数组 - 可能无法初始化可变大小的对象

swift - 使用 Parse 和 Swift 返回具有指针 ID 的所有对象

c++ - 访问旧的堆栈帧

c++ - 如何比较并获取两个列表中未包含的值

带有多个字符定界符的 Java String.split

python - 循环处理字符串