第二次使用 strcat 后堆损坏

Chr*_*ris 2 c++

这让我发疯,因为我没有看到我在这里犯了什么愚蠢的错误。

在下面的片段中(注意这只是一个来自更大方法的测试片段),我基本上只是尝试复制从 SQL 方法中检索到的字符串,然后如果用户在方法中指定了额外的列数, 附加一个分隔符(在本例中为分号)和附加字符串:

//...
char** pLocalArray;
char buff[512];
//... pLocalArray is allocated

// The semicolon is replaced by a variable passed into the function, but just putting this for simplicity
char delimeterStr[2] { ';', '\0' };

for (int uCol = 0; uCol < numCols; uCol++)
{
    if (uCol >= 1)
    {
        const char* test2 = "1704EB18-FE46-4AE4-A90F-06E42C3EE07A"; // Just a test GUID
        memcpy(buff, test2, 37); // Just testing some logic, copy the string into the buffer 

        strcat(pLocalArray[uRow], delimeterStr); // This works just fine if I stop here
        // strcat(pLocalArray[uRow], buff); // ***** If I uncomment out this line, it throws a heap exception

        std::cout << "Check 3 -- Output is: " << pLocalArray[uRow] << endl; // Output: MyFirstString|MySecondString|MyThirdString;1704EB18-FE46-4AE4-A90F-06E42C3EE07A
        std::memset(buff, '\0', sizeof(buff));
        std::cout << "Check 4 -- Output is: " << pLocalArray[uRow] << endl; //Sanity check - MyFirstString|MySecondString|MyThirdString;1704EB18-FE46-4AE4-A90F-06E42C3EE07A
    }
    else
    {
        const char* test = "MyFirstString|MySecondString|MyThirdString";
        memcpy(buff, test, 43);
        pLocalArray[uRow] = _strdup(buff);

        std::cout << "Check -- Output is: " << pLocalArray[uRow] << endl; // Output: MyFirstString|MySecondString|MyThirdString
        std::memset(buff, '\0', sizeof(buff));
        std::cout << "Check 2 -- Output is: " << pLocalArray[uRow] << endl; //Sanity check - Output: MyFirstString|MySecondString|MyThirdString
    }
}
//...
Run Code Online (Sandbox Code Playgroud)

但是,正如您从评论中看到的那样,当我使用第二个strcat调用时,它会引发异常。我不明白为什么strcat在分隔符上做这个工作得很好,但是附加分隔符然后立即附加 GUID 字符串不起作用。有人可以向我指出我做错了什么或没有考虑到什么吗?

Adr*_*ica 5

您可能误解了该strdup函数的工作原理。在以下行中:

    pLocalArray[uRow] = _strdup(buff);
Run Code Online (Sandbox Code Playgroud)

调用它来为初始分配内存pLocalArray[uRow],分配的空间量将是字符串的实际长度buff,解释为以 -结尾的nul字符数组;这将是"MyFirstString|MySecondString|MyThirdString"文字的长度,而不是buff数组的指定大小。

然后,当您稍后尝试向其附加一个字符串时,您会溢出分配的空间(您的第一个似乎strcat只工作,但它仍然是未定义的行为)。

要允许最多 511 个字符(加上 -nul终止符)的空间,您将需要如下代码:

    pLocalArray[uRow] = malloc(sizeof(buff)); // Allocate full size of "buff"
    strcpy(pLocalArray[uRow], buff); // then copy the strung data
Run Code Online (Sandbox Code Playgroud)