删除 getenv() 返回的 char 数组
我是否应该释放为 char 数组分配的内存(由 char * getenv( char * ) 函数返回的指针)?哪种方式 - C free()
还是 C+ delete []
?如果没有——为什么?
我的意思是:
char * ptr = getenv( "LS_COLORS" );
cout << ptr << endl;
delete [] ptr; //Is this or free() call needed?
谢谢。
Should I free the memory allocated for the char array, pointer to which is returned by the char * getenv( char * )
function? And which way - C free()
or C+ delete []
? If no - why?
I mean:
char * ptr = getenv( "LS_COLORS" );
cout << ptr << endl;
delete [] ptr; //Is this or free() call needed?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原始数据存储在
environ
变量中(它是一个char*数组,包含所有环境变量及其值),getenv()
只搜索相应的变量name 并从environ
变量返回其值的位置,因此您不必释放它,否则可能会发生未定义的行为。The original data is stored in the
environ
variable (which is an array of char* and contains all environment variables with their values),getenv()
only search for the corresponding variable name and returns the position of its value from theenviron
variable, so you don't have to free it, otherwise undefined behavior may be occurred.Getenv 返回指向您的进程环境的指针。它不需要被释放,而且最好不要释放。 (删除和释放可能足够聪明,什么都不做,但破坏你的环境并不是一个好主意。)
Getenv returns a pointer to your processes environment. It does not need to be deallocated, and it is probably a good idea not to. (delete and free are probably smart enough to do nothing, but corrupting your environment is not a good idea.)