检测到堆损坏(字符串导致堆损坏)| C++

Heap corruption detected (String makes heap corruption) | C++

我不知道为什么这个函数会导致堆损坏,我确定函数 copyFile 与错误无关。请检查并帮助我TT

    void copyFileToFolder(char* fileName, char* folderName)
{
    char backSlash = '\';
    char *nameOfFileWithBackSlashInHead = strrchr(fileName, backSlash);
    char *newFileName = strcat(folderName, nameOfFileWithBackSlashInHead);
    FILE* f = fopen(newFileName, "wb");
    if (!f)
    {
        cout << "Folder does't exist";
        return;
    }
    fclose(f);
    copyFile(fileName, newFileName);
}

strcat 将附加到 folderName,这是有问题的。 folderName 来自外部,如果写入超出其分配的存储空间,可能会导致内存损坏。请参阅 strcat 附加到其第一个输入参数以及 returns 它。

将您的函数签名更改为

void copyFileToFolder(const char* fileName, const char* folderName)

并创建一个新变量来存储附加的文件名。