我应该释放/删除 getenv() 返回的 char* 吗?
char * val;
val = getenv("ENV_VAR_NAME");
上面是获取环境变量的代码,如果不释放 getenv(char*) 返回的内存,会导致内存泄漏吗?如果不是,请回答为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不应该。标准 7.20.4.5 说:
我相信删除内容已包含在粗体文本中。
No you shouldn't. Standard 7.20.4.5 says :
I believe deletion is covered by the text in bold.
你不应该释放它。这是手册页的片段:
别碰它!
You should not free it. This is a snippet from the man page:
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.
你不应该删除它。 Getenv 只是从 char* 数组(char** environ,如果我没记错的话)获取一个值,该数组包含每个环境变量。删除它们会导致未定义的行为。
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.
可能最好的原因是标准没有说可以。仅仅因为函数返回一个指针并不意味着该指针可以有效地传递给
free
。除非函数的文档明确指出该函数“就像通过调用 malloc 一样”分配内存并返回指向该内存的指针,否则您必须假设该指针对于传递给 realloc 无效 或免费
。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 callingmalloc
" and returns a pointer to that memory, you must assume the pointer is not valid to pass torealloc
orfree
.