c++environment-variablesgetenv

getenv in C++ returns wrong values


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


Solution

  • 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")