Home > Software design >  Are environment variables in C writeable?
Are environment variables in C writeable?

Time:01-25

The function getenv(const char * key) returns char *.

Does it mean that I can change some character inside of returned char array?

For example

char * name = getenv("PROJECT_NAME");

if(name && strlen(name) > 0) name[0] = 'P';

Is it good practice to do this? Should I make my own copy of array? Where are environment variables stored (what part of memory)? Are they avaible till the end of program?

Thank you for your answer.

CodePudding user response:

In https://en.cppreference.com/w/cpp/utility/program/getenv:

Modifying the string returned by getenv invokes undefined behavior.

So you can modify it but doing so leads to undefined behavior. So you shouldn't do it

  •  Tags:  
  • Related