将strcpy_s()和strcat_s()与动态分配的字符串结合使用

时间:2019-05-09 09:15:54

标签: c++ visual-studio

在下面的代码中,我尝试创建一个获取动态分配的字符串的函数。该函数将要求用户输入另一个也会动态分配的字符串。最后,您将分配另一个大字符串,该初始字符串将被复制到该大字符串,然后是第二个字符串。

我的问题:在函数中,我使用strcpy_s()strcat_s()复制和连接字符串,并且出于神秘的原因,有2个函数覆盖了程序...

#include<iostream>

using namespace std;
void addChars(char** theStr);

void main()
{
    // const def
    const int STR_SIZE = 10;
    char* str = new char[STR_SIZE + 1];

    cout << "Enter 10 chars:" << endl;
    cin.getline(str, STR_SIZE + 1);

    if (cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max());
    }

    addChars(&str);

    cout << str << endl;

    system("pause");
}

void addChars(char ** theStr)
{
    int toAdd;
    int oldSize;
    char* AddStr;
    char* tempstr;

    cout << "How many chars to add:" << endl;
    cin >> toAdd;
    AddStr = new char[toAdd + 1];

    cout << "Enter the chars: " << endl;
    cin.clear();
    cin.ignore();
    cin.getline(AddStr, toAdd + 1);

    // check the src string size
    oldSize = strlen(*theStr);

    // alloc the big new str for the 2 exis strings
    tempstr = new char[(oldSize + toAdd) + 1];

    // copy the old string to the new
    strcpy_s(tempstr, oldSize, *theStr);

    // add the AddStr to the string
    strcat_s(tempstr, toAdd, AddStr);

    // delete the older and updates the new address
    delete[] * theStr;
    *theStr = tempstr;
}

3 个答案:

答案 0 :(得分:1)

strcpy_s(tempstr, oldSize, *theStr);

应该是

strcpy_s(tempstr, (oldSize + toAdd) + 1, *theStr);

我引用了此文档(https://en.cppreference.com/w/c/string/byte/strcpy),它指出您应该指定目标大小,而不是源大小。

errno_t strcpy_s(char *限制目标,rsize_t destsz,const char *限制src);

答案 1 :(得分:0)

strcpy_s(tempstr, oldSize, *theStr);

断言失败,oldSize太小。

上一行是

tempstr = new char[(oldSize + toAdd) + 1]; 

您应该将oldSize + toAdd作为第二个参数传递给strcpy_s。

话虽如此,这段代码是当今如何不使用C ++编写代码的最佳示例。

答案 2 :(得分:0)

此行:

// add the AddStr to the string
strcat_s(tempstr, toAdd, AddStr);

应为:

// add the AddStr to the string
strcat_s(tempstr, oldSize, AddStr);

Point (2)

因为要在oldString的oldSize Bytes之后并置新字符串AddStr,该字符串已在tempstr中复制。

但这与现代C ++相距甚远。 使用std :: string代替

否则,应将其标记为 C C11 ,而不是C ++