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

yeah_well

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

Some programmer dude

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why does RegEx.test changes the result in subsequent calls?

Why was getenv standardised but not setenv?

Why does getenv() return a non-const string

why does a simple print(os.getenv("HOME")) get nil?

getenv("cc") is returning NULL , why?

why is getenv MT-safe in man page?

In C, why is the pointer returned by getenv automatically reclaimed?

why does os.Getenv("SERVER_SOFTWARE") returns blank string for me?

Having trouble mocking System.getenv calls in junit

PHP: difference between getenv() and apache_getenv()

On Java 9 why is the output from System.getenv() incomplete in jshell?

Why is my config item not populating from my getenv() entry in codeigniter?

Why System.getenv("HOMEPATH") return not absolute path on Windows?

Why MYVAR=something wont appear in printenv? Is this related to getenv function?

getenv() is some times returning false in CodeIgniter 4. Why?

why a non root user call getenv on an exported variable returns nil

SetEnvironmentVariable() does not seem to set values that can be retrieved by getenv()

uwsgi: os.getenv("PATH") does not work with /etc/environment in linux

How does the *getenv function actually works when passing "PATH" as parameter?

C - scanf() and then getenv()

secure_getenv() on macOS

getenv Not Working for COLUMNS and LINES

How to mock getenv in pytest?

Implementing getenv() in ATS

value of getenv() not working in strtok()

C++ getenv and setenv

Mysterious getenv() seg faults

Why does NetBSD grep slow down nearly 15x on subsequent calls

Why does the first call to readline() slow down all subsequent calls to fnmatch()?