char * val;
val = getenv("ENV_VAR_NAME");
above is a code to get environment variable, will it cause memory leak if I dont free memory returned by getenv(char*) ? If no then please answer why?
Return ValueThe getenv() function returns a pointer to the string containing the value for the specified varname in the current environment.
Return Value The getenv() function returns a pointer to the c-string containing the value of the environment variable that corresponds to env_var . If no environment variable is found, it returns a null pointer . Environment variables are system-wide variables that are available to all processes in the system.
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.
You should not free it. This is a snippet from the man page:
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.
Don't touch it !
No. You don't control its storage. Typically, it's a pointer to a static array that is reused multiple times. For this reason, you should copy it if you plan to store it for later use (you should ensure this copy is freed properly).
Unless the documentation explicitly says you may free a pointer, you should not.
You shouldn't delete it. Getenv just get a value from a char* array (char** environ, if I remember correctly), that contains every environment variable. Deleting them causes undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With