免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3513 | 回复: 4
打印 上一主题 下一主题

请问我这个malloc分配的内存,该如何释放 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-08-23 14:27 |只看该作者 |倒序浏览

  1. struct entry
  2. {
  3.        char* attrName;
  4. }

  5. entry* visitEntry()
  6. {
  7.     entry *tmp = (entry*)malloc(100);

  8.     /*do something with tmp*/

  9.     attr(tmp);

  10.     return tmp;

  11. }

  12. node* attr(entry* node)
  13. {
  14.     char *tmpAttr = (char*)malloc(100);

  15.     /*do something with tmpAttr*/
  16.     node->attrName = tmpAttr;
  17.     return node;
  18. }
复制代码
entry()会被调用好多次,请问这两个函数中的内存我该如何释放

论坛徽章:
0
2 [报告]
发表于 2011-08-23 15:02 |只看该作者
在每次使 entry*    tmp    重定向的时候,释放掉它之前的空间,如:
23   node->attrName = tmpAttr;
前 free下 node指针。
不知道 说的对不对。

论坛徽章:
1
天蝎座
日期:2013-12-06 18:23:58
3 [报告]
发表于 2011-08-23 15:30 |只看该作者
有几个malloc就free几次,至于顺序,应该是 后malloc的先free

论坛徽章:
0
4 [报告]
发表于 2011-08-23 15:39 |只看该作者
从内到外释放就可以了。

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct tgentry
{
       char* attrName;
}entry;

entry* attr(entry* node)
{
    char *tmpAttr = (char*)malloc(100);
    printf("tmpAttr=%p\n",tmpAttr);
    /*do something with tmpAttr*/
    node->attrName = tmpAttr;
    printf("node->attrName=%p\n",node->attrName);
    memset(node->attrName ,0x00,100);
    strcpy(node->attrName ,"testhello");
    printf("node=%p\n",node);
    return node;
}

entry* visitEntry()
{
    entry *tmp = (entry*)malloc(100);
    printf("tmp01=%p\n",tmp);
    /*do something with tmp*/

    attr(tmp);
    printf("tmp02=%p\n",tmp);
    return tmp;

}
int main( int argc,char *argv[] )
{
    entry *tmp;
    tmp=visitEntry();
    printf("%s\n",tmp->attrName);
    printf("tmp03=%p\n",tmp);
    printf("tmp->attrName=%p\n",tmp->attrName);
    free(tmp->attrName);
    free(tmp);

    return 0;
}

运行结果如下:
tmp01=003E3D50
tmpAttr=003E2430
node->attrName=003E2430
node=003E3D50
tmp02=003E3D50
testhello
tmp03=003E3D50
tmp->attrName=003E2430

论坛徽章:
0
5 [报告]
发表于 2011-08-23 18:26 |只看该作者
非常感谢楼上
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP