请教一个关于malloc申请与释放内存的问题

fredshao 2012-05-12 04:36:29
刚刚看《linux程序设计》这本书,里面有一段代码是这样的


if(argc == 3)
{
char *string;
value = argv[2];

string = malloc(strlen(var)+strlen(value) + 2);

if(!string){
fprintf(stderr,"out of memory\n");
exit(1);
}

sprintf(string,"%s=%s",var,value);
printf("Calling putenv with: %s\n",string);

if(putenv(string) != 0){ //putenv 出错返回 -1
fprintf(stderr,"putenv failed\n");
free(string);
exit(1);
}

value = getenv(var);
if(value)
{
printf("New value of %s is %s\n",var,value);
}
else
{
printf("New value of %s is NULL??\n",var);
}
}




上面代码,如果putenv返回0,那free函数就不执行了,那申请的这段内存,在if结束的时候自动释放?
记得在哪里看过说malloc是在堆上申请内存的,需要手动释放,程序中再没有其他的free了,那这段内存是在什么时候释放?
...全文
91 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
proorck6 2012-05-13
  • 打赏
  • 举报
回复
我觉得是这段代码错了,书上的东西也不一定全都对啊。
qq120848369 2012-05-12
  • 打赏
  • 举报
回复

RETURN VALUE
The putenv() function returns zero on success, or nonzero if an error occurs.

NOTES
The libc4 and libc5 and glibc 2.1.2 versions conform to SUSv2: the pointer string given to putenv() is used. In particular, this
string becomes part of the environment; changing it later will change the environment. (Thus, it is an error is to call putenv() with
an automatic variable as the argument, then return from the calling function while string is still part of the environment.) However,
glibc 2.0-2.1.1 differs: a copy of the string is used. On the one hand this causes a memory leak, and on the other hand it violates
SUSv2. This has been fixed in glibc 2.1.2.

唯一需要注意的就是putenv的字符串不要修改它了,因为putenv直接把该字符串存在environment里,而不是strdup一个副本,这很重要。

另外环境变量属于伴随进程生死的,进程结束则内存释放,无论什么内存都是这样的,不需要担心。

这里之所以返回非0要释放是因为putenv失败了,自然要自己释放掉,否则就内存泄露了。
W170532934 2012-05-12
  • 打赏
  • 举报
回复
malloc申请的内存,如果不是手动free掉的话,就一直等到程序结束,操作系统回收程序的所有的资源的时候释放。程序结束,操作系统会回收当初分配给程序的所有的资源。

69,377

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧