c - 如何正确释放指针

c - 如何正确释放指针

这是我编写的一个函数:

uint32_t file_list(char *path, char ***ls){

DIR *dp;

//uint32_t i;

struct stat fileStat;

struct dirent *ep = NULL;

uint32_t len, count = 0;

int file = 0;

*ls = NULL;

dp = opendir (path);

if(dp == NULL){

fprintf(stderr, "no dir: %s\n", path);

exit(1);

}

ep = readdir(dp);

while(NULL != ep){

count++;

ep = readdir(dp);

}

rewinddir(dp);

*ls = calloc(count, sizeof(char *));

count = 0;

ep = readdir(dp);

while(ep != NULL){

if((file = open(ep->d_name, O_RDONLY)) < 0){

perror("apertura file");

exit(1);

}

if(fstat(file, &fileStat) != 0){

perror("filestat");

free(*ls);

close(file);

exit(EXIT_FAILURE);

}

close(file);

if(S_ISDIR(fileStat.st_mode)){

len = strlen(ep->d_name);

(*ls)[count] = malloc(len+5); /* lunghezza stringa + "DIR \n" */

strcpy((*ls)[count], "DIR "); /* copio DIR */

strcat((*ls)[count++], ep->d_name); /* concateno la stringa DIR con il nome della dir */

ep = readdir(dp);

}

else{

(*ls)[count++] = strdup(ep->d_name);

ep = readdir(dp);

}

}

/*for(i=0; i

free((*ls)[count]);

}*/

(void)closedir(dp);

return count;

}

进入我拥有的主程序char **files,然后我得到计数​​的部分count = file_list("./", &files);

是我的问题是什么?

每个人都知道它们(指针)可能引用的动态分配的内存必须被释放,但如果我释放指针(使用 for 循环)然后进入主程序,我在文件列表期间出现意外行为(重复的文件名,没有文件名等)。实际上,如果我不释放指针,所有指针都可以正常工作。

所以我的问题是:如何释放这些指针?

提前致谢!

✧ 相关推荐 ✧

新加坡主要的媒体有哪些?【新加坡百问百答45】
Microsoft 365安卓

新加坡主要的媒体有哪些?【新加坡百问百答45】

📅 07-27 👁️ 6257
《坦克世界》技能学习顺序推荐
365bet体育官网网址

《坦克世界》技能学习顺序推荐

📅 07-27 👁️ 7725
硬盘温度多少正常? 电脑硬盘能耐受的最高温度是多少?