0

I would like to write my program in 2 different paths. So, I proceeded like that :

std::string path1 = strcat(std::getenv("APPDATA"),"\\myprog.exe") ;
std::string path2 = strcat(std::getenv("APPDATA"),"\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\myprog.exe") ;

When I print, I get :

C:\Users\thispc\AppData\Roaming\myprog.exe
C:\Users\thispc\AppData\Roaming\myprog.exe\Microsoft\Windows\Start Menu\Programs\Startup\myprog.exe

instead of :

C:\Users\thispc\AppData\Roaming\myprog.exe
C:\Users\thispc\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\myprog.exe

Solution by Dietmar Kühl :

std::string path1 = std::getenv("APPDATA") + std::string("\\myprog.exe");

Explanation by Oliver Charlesworth : strcat() changes the 1st variable

  • 2
    You clearly change the result of the first call to `std::getenv()` (which, I think, is actually illegal). Did you mean to write something like `std::string path1 = std::getenv("APPDATA") + std::string("\\myprog.exe");`? – Dietmar Kühl Dec 16 '17 at 18:17
  • 3
    `strcat` modifies the string pointed to by its first argument. That's legal in general, but not in this particular case - you don't know how much storage was allocated for it. – Oliver Charlesworth Dec 16 '17 at 18:17

1 Answers1

0

What is happening here is that std::getenv("APPDATA") gives you a pointer to a already written string somewhere in memory, that means the pointer returned by this function will always be the same.

Thus when you do strcat(std::getenv("APPDATA"),"\\myprog.exe") you basically concatenate that stored string in memory with "\\myprog.exe". So when you make a second call of std::getenv("APPDATA") you will get the concatenated string.

To solve this problem you should copy the string at std::getenv("APPDATA")