- 论坛徽章:
- 0
|
学习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,否则会导致内存泄露。不知道我的理解对不对。
请指出。 感谢大家。 |
|