Ok, so I need to concatenate results to getenv. I am not allowed to define any other variables. If getenv returns heap pointers, then can I realloc it, to concatenate? Yes, or not?
-
1Short answer: No. – Steve Summit Nov 15 '19 at 22:34
-
Just try it and tell us what happened (if your computer still work). – Orace Nov 15 '19 at 22:39
-
@Orace Poor advice. Too often, when people "just try it", something seems to work even though it's undefined, and they learn wrong lessons. – Steve Summit Nov 15 '19 at 22:46
3 Answers
As per the documentation:
As typically implemented,
getenv()
returns a pointer to a string within the environment list. The caller must take care not to modify this string, since that would change the environment of the process.
Modifications also include calling free()
. This documentation is effectively explaining that you don't own the pointer, you can't alter it, you can't release it. It's to be considered read-only.
Instead use strdup()
or something similar to make a copy if necessary, and that one you will own.
Further, the value returned by getenv()
is only valid until the next call is made, at which point it's invalidated. If you need to retain or alter this information you must make a copy.

- 208,517
- 23
- 234
- 262
No
From the get_env manpage:
As typically implemented, getenv() returns a pointer to a string within the environment list. The caller must take care not to modify this string, since that would change the environment of the process.

- 222
- 2
- 18
See http://www.cplusplus.com/reference/cstdlib/getenv/
The string pointed by the pointer returned by this function shall not be modified by the program. Some systems and library implementations may allow to change environmental variables with specific functions (putenv, setenv...), but such functionality is non-portable.

- 7,822
- 30
- 45