0

I came across the function getenv from c recently, which takes an environment variable as argument and returns the corresponding path.

const char * path = getenv("HOME");
....

This got me thinking if this could cause a memory leak. Because the function returns a value which has to be dynamically allocated because the value exists after the function is out of scope. It would be deallocated after the function call went after scope if it was allocated on the function call stack right? If that's the case should I call free() or an appropriate deallocator function to avoid memory leak? If it's not dynamically allocated, then is it something like an anonymous constant value? I am sort of confused on how this works and this sort of function calls are very common in C that's why I am sort of worried about memory leaks and such.

Vahan
  • 166
  • 13
  • 1
    `getenv` returns a pointer to the value, that's all you can know. If you want to know how exactly that works in _your_ environnment, you need to get the appropriate source code and see how it has been implemented, or step into the assembly code with your favorite debugger etc.. Basically you don't need to worry. If freeing the returned pointer was required, then the documentation would clearly state that. – Jabberwocky Dec 18 '20 at 11:28
  • 1
    See the [manpage](https://man7.org/linux/man-pages/man3/getenv.3.html) – Mark Benningfield Dec 18 '20 at 11:28
  • 3
    Does this answer your question? [Should I free/delete char\* returned by getenv()?](https://stackoverflow.com/questions/4237812/should-i-free-delete-char-returned-by-getenv) – Mark Benningfield Dec 18 '20 at 11:50
  • Most likely, all the values (strings) of the environment variables are already in your process’ memory, because they were set up during loading of the program, and `getenv` just returns a pointer to the existing string. So there is no need to free it; it is intentionally sitting in program memory for all of program execution. Some may have been added later with `setenv`, but their memory is also being held long-term, and `getenv` just returns a pointer to it. If for some reason `getenv` is implemented to return a short-term copy of the string, then it will manage that memory itself. – Eric Postpischil Dec 18 '20 at 12:24

1 Answers1

2

According to the NOTES section of the manual getenv(3):

The implementation of getenv() is not required to  be  reentrant.   The
string pointed to by the return value of getenv() may be statically al‐
located, and  can  be  modified  by  a  subsequent  call  to  getenv(),
putenv(3), setenv(3), or unsetenv(3).

In the event the variable is statically allocated, this means that the variable holding the pointer will reference to an address that already exists in the code, hence not dynamically allocating it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
Ra'Jiska
  • 979
  • 2
  • 11
  • 23