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?
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.
Probably the best reason why is that the standard does not say you can. Just because a function returns a pointer does not mean that pointer is valid to pass to free
. Unless the documentation of a function says specifically that the function allocates memory "as if by calling malloc
" and returns a pointer to that memory, you must assume the pointer is not valid to pass to realloc
or free
.
精彩评论