免费注册 查看新帖 |

Chinaunix

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

[C] APUE:程序2.2-动态分配空间--内存泄露吗??? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-05 21:37 |只看该作者 |倒序浏览
学习APUE的第二章,发现“程序2.2 为路径名动态地分配空间” 感觉应该会导致内存泄露。例子如下:

#define        PATH_MAX_GUESS        1024        /* if PATH_MAX is indeterminate */

char * path_alloc(int *size)
                        /* also return allocated size, if nonnull */
{
    char        *ptr;

   if (pathmax == 0) {                /* first time through */
        errno = 0;
        if ( (pathmax = pathconf("/", _PC_PATH_MAX)) < 0) {
        if (errno == 0)
                pathmax = PATH_MAX_GUESS;        /* it's indeterminate */
        else
                err_sys("pathconf error for _PC_PATH_MAX");
       } else
        pathmax++;                /* add one since it's relative to root */
   }

  if ( (ptr = malloc(pathmax + 1)) == NULL)     //这里只有malloc
       err_sys("malloc error for pathname");

  if (size != NULL)
      *size = pathmax + 1;
return(ptr);
}

//测试函数,APUE提供的。 没有相应的free
#include        "ourhdr.h"

int  main(void)
{
        char        *ptr;
        int                size;

        if (chdir("/usr/spool/uucppublic") < 0)
                err_sys("chdir failed");

        ptr = path_alloc(&size);        /* our own function */
        if (getcwd(ptr, size) == NULL)
                err_sys("getcwd failed");

        printf("cwd = %s\n", ptr);
        exit(0);
}


我的理解是,如果调用了malloc,必定有相应的free,否则会导致内存泄露。不知道我的理解对不对。

请指出。 感谢大家。

论坛徽章:
0
2 [报告]
发表于 2008-06-05 21:39 |只看该作者
有申请没有释放,就是内存泄露

论坛徽章:
0
3 [报告]
发表于 2008-06-05 21:47 |只看该作者
对的,会造成内存泄露。
但是由于这是一个小的示例程序,在退出main函数之后,操作系统会回收这个进程的所有资源。包括泄漏了的内存,所以不会造成什么大的影响。但是自己在写一个可能会运行较长时间的程序会要注意这点。

论坛徽章:
0
4 [报告]
发表于 2008-06-06 12:26 |只看该作者

回复 #1 c_fanatic 的帖子

能给解释下

  1. (pathmax = pathconf("/", _PC_PATH_MAX)) < 0
复制代码

顺便大概说说整个函数的作用,谢谢拉.
我也再看AUPE呢.

论坛徽章:
0
5 [报告]
发表于 2008-06-06 12:50 |只看该作者

回复 #4 dianlongliu 的帖子

Hi,你可以 man pathconf一下:
long int pathconf(const char *pathname,int parameter)
     The  fpathconf()  and  pathconf()  functions  determine  the
     current value of a configurable limit or option ( variable )
     that is associated with a file or directory.

     For pathconf(), the path argument points to the pathname  of
     a file or directory.

论坛徽章:
0
6 [报告]
发表于 2008-06-06 16:50 |只看该作者

回复 #5 c_fanatic 的帖子

嘿嘿,man了,但是还是不明天拉,等下再看看书上如何说的把.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP