clibc

Should I free/delete char* returned by getenv()?


char * val;
val = getenv("ENV_VAR_NAME");

The above is code to get an environment variable. Will it cause a memory leak if I don't free the memory returned by getenv(char*)? If no then please explain why?


Solution

  • No you shouldn't. Standard 7.20.4.5 says :

    The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function.

    I believe deletion is covered by the text in bold.