1

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!

43.52.4D.
  • 950
  • 6
  • 14
  • 28

1 Answers1

1

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.

Mike Woolf
  • 1,210
  • 7
  • 11
  • The [MSDN ref](http://msdn.microsoft.com/en-us/library/windows/desktop/bb773571(v=vs.85).aspx) warns: "Misuse of this function can lead to a buffer overrun. We recommend the use of the safer PathCchCombine or PathCchCombineEx function in its place." Using the same 'in' and 'out' buffer is not a buffer overrun, but nevertheless falls under "asking for trouble". – Jongware Dec 15 '13 at 00:08
  • Actually, since name points to somewhere in the middle of the mystring buffer, name is actually not large enough to hold a max sized output string. A buffer overrun is definitely possible the way this code is written. – Mike Woolf Dec 15 '13 at 00:10
  • I still don't really understand why mypath is being modified when the code doesn't even mention it at PathCombineA(). What exactly does PathCombineA() do that changes mypath? I'm no expert at C++, so explain it simply if possible. Thanks! – 43.52.4D. Dec 15 '13 at 00:14
  • @43.52.4D.: your pointer *name* points to 'inside' `mypath`, as requested by [PathFindFileNameA](http://msdn.microsoft.com/en-us/library/windows/desktop/bb773589(v=vs.85).aspx) – Jongware Dec 15 '13 at 00:18
  • The issue is that PathFindFileNameA returns a pointer into the middle of the mystring. In other words, name is a synonym for the last part of the mystring array. When you used name as the output buffer for PathCombineA, you effectively used part of mystring as the output buffer. – Mike Woolf Dec 15 '13 at 00:19
  • You're running up against the usual confusion about the relationship between pointers and arrays encountered by newcomers to C. – Mike Woolf Dec 15 '13 at 00:27