0

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

EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
yeah_well
  • 130
  • 1
  • 6
  • Yeah i got it.Thanks. – yeah_well Jan 27 '20 at 10:11
  • 4
    According to the C standard, modifying a string returned by `getenv()` - for example, by appending something to it using `strcat()` - gives undefined behaviour. Practically, if `getenv()` uses a `static` pointer internally, the effect of `strcat()` may be to modify the string seen by other calls of `getenv()` - since they may all return the same pointer. – Peter Jan 27 '20 at 10:37

1 Answers1

7

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621