Chinaunix

标题: APUE:程序2.2-动态分配空间--内存泄露吗??? [打印本页]

作者: c_fanatic    时间: 2008-06-05 21:37
标题: APUE:程序2.2-动态分配空间--内存泄露吗???
学习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,否则会导致内存泄露。不知道我的理解对不对。

请指出。 感谢大家。
作者: net_robber    时间: 2008-06-05 21:39
有申请没有释放,就是内存泄露
作者: scutan    时间: 2008-06-05 21:47
对的,会造成内存泄露。
但是由于这是一个小的示例程序,在退出main函数之后,操作系统会回收这个进程的所有资源。包括泄漏了的内存,所以不会造成什么大的影响。但是自己在写一个可能会运行较长时间的程序会要注意这点。
作者: dianlongliu    时间: 2008-06-06 12:26
标题: 回复 #1 c_fanatic 的帖子
能给解释下

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

顺便大概说说整个函数的作用,谢谢拉.
我也再看AUPE呢.
作者: c_fanatic    时间: 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.
作者: dianlongliu    时间: 2008-06-06 16:50
标题: 回复 #5 c_fanatic 的帖子
嘿嘿,man了,但是还是不明天拉,等下再看看书上如何说的把.




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2