Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

libc

 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?

like image 688
SunnyShah Avatar asked Nov 21 '10 12:11

SunnyShah


People also ask

Does Getenv return strings?

Return ValueThe getenv() function returns a pointer to the string containing the value for the specified varname in the current environment.

What does Getenv return in C?

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.


4 Answers

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.

like image 79
icecrime Avatar answered Sep 26 '22 07:09

icecrime


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 !

like image 35
Nicolas Viennot Avatar answered Sep 24 '22 07:09

Nicolas Viennot


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.

like image 9
Matthew Flaschen Avatar answered Sep 24 '22 07:09

Matthew Flaschen


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.

like image 5
Raveline Avatar answered Sep 26 '22 07:09

Raveline