c++cgetenv

Why does strcat to getenv() changes subsequent getenv() calls?


I use getenv() in my c code.

Here is the code I use

#include<windows.h>
#include<stdio.h>

int main()

{
    char *path=getenv("USERPROFILE");
    strcat(path,"\\bullshit");
    char *newpath=getenv("USERPROFILE");
    printf("%s",newpath);
}

The result of the print statement is

C:\Users\username\bullshit

Why does the getenv() call to environment variable change due to strcat?

NOTE: I am using minw-gcc compiler 32-bit on windows 8.1 system


Solution

  • You don't own the string returned by getenv, you can't modify it (like for example appending something to it).

    If you need to modify it, then copy it to memory you own and can modify, like an array:

    char path[PATH_MAX];
    strcpy(path, getenv(...));
    strcat(path, ...);
    

    As noted this can lead to buffer-overflows, so a safer method could be to use strncpy. But then remember there's a case where it won't add the string null-terminator so it needs to be added explicitly.