i am re-implimenting the unix ls command, but when i test for leaks it says:Process 44151: 248 nodes malloced for 45 KB, Process 44151: 28 leaks for 560 total leaked bytes. so i tried to free the pwd, and grp. but it says the i am freeing memory that was never allocated.
static int one(const struct dirent *unused)
{
(void)unused;
return (1);
}
void ls_l(void)
{
struct stat statbuf;
struct group *grp;
struct passwd *pwd;
struct dirent **sd;
int n;
int i;
pwd = getpwuid((geteuid()));
n = scandir(".", &sd, one, alphasort);
i = 1;
while (i < n)
{
while (strncmp(sd[i]->d_name, ".", 1) == 0)
i++;
if (stat(sd[i]->d_name, &statbuf) == 0)
{
ft_perm(sd[i]->d_name);
ft_printf(" %-2d %4s ", statbuf.st_nlink, pwd->pw_name);
if ((grp = getgrgid(statbuf.st_gid)) != NULL)
ft_printf(" %-8.8s %5d %s %s\n",grp->gr_name,
(int)statbuf.st_size,ft_group(ctime(&statbuf.st_mtime)),
sd[i]->d_name);
else
ft_printf(" %-8d %5d %s %s\n", statbuf.st_gid,
(int)statbuf.st_size,ft_group(ctime(&statbuf.st_mtime)),
sd[i]->d_name);
}
free(sd[i]);
i++;
}
free(sd);
}
while (strncmp(sd[i]->d_name, ".", 1) == 0)
i++;
// code
free(sd[i]);
There's the cause of your memory leak. You're never freeing the elements of sd whose filenames start with a period.
Also, I'd use sd[i]->d_name[0] == '.'
for that comparison. strncmp()
is overkill for this. A fixed version of your loop:
for (int i = 0; i < n; i += 1) {
while (i < n && sd[i]->d_name[0] == '.') {
free(sd[i++]);
}
if (i == n) {
break;
}
// code
free(sd[i]);
}
free(sd);
In addition, this handles cases where every file returned is a dotfile, where your original one would result in reading past the end of the sd
array in that situation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.