c++charpath-combine

Why is this string being mysteriously modified?


Please forgive me if the answer to this is simple, but I have NO idea what is causing this. The PathCombineA function is somehow modifying the mypath variable. If you run the program you will see what I mean. (You must link Shlwapi.lib)

#include <Windows.h>
#include <Shlwapi.h>
#include <iostream>

using namespace std;

int main()
{
    CHAR temp[MAX_PATH];
    CHAR mypath[MAX_PATH]; 

    GetModuleFileNameA(NULL, mypath, MAX_PATH);
    GetTempPathA(MAX_PATH, temp);

    LPSTR name = PathFindFileNameA(mypath);

    cout << mypath << endl;

    PathCombineA(name, temp, name);

    cout << mypath << endl;

    getchar();
    return 0;
}

Output before PathCombineA

C:\Users\Owner\Desktop\etc\Debug\etc.exe


Output after PathCombineA

C:\Users\Owner\Desktop\etc\Debug\C:\Users\Owner\AppData\Local\Temp\etc.exe


If you guys have any idea what is going on, please tell me!

Thanks!


Solution

  • PathFindFileNameA is returning a pointer to the last part of the string in mypath. You then pass that pointer into the mystring buffer as the output parameter to PathCombineA.

    If you don't want mystring to be modified, you'll need yet another buffer to hold the output of PathCombineA.