C++

问题描述 投票:0回答:1

I dont know why this function has made the heap corruption, I'm sure that the function copyFile isn't related to the error. Please check and help me 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);
}
c++ string heap-corruption
1个回答
1
投票

The strcat will append to folderName which is problematic. folderName is comming from outside and it might result in memory corruption if you write beyond its allocated storage. See strcat appends to its first input argument and also returns it.

Change your function signature to

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

and make a new variable to store appended file name.

© www.soinside.com 2019 - 2024. All rights reserved.