Im trying to write and implement the command 'tree -pugs' in linux on C languange. It running well but I have leak issues when I run the program with valgrind flag. I have tried to free the variable but I got segmentation fault.
heres my code:
int count_dir = 0;
int count_file = 0;
int count_total = 0;
char *user_name = "";
char *group_name = "";
long file_size = 0;
char last_type;
char *pre_name;
mode_t pre_mode;
int tree_walk(const char *name, const struct stat *status, int type, struct FTW *ftw)
{
if (type == FTW_D || type == FTW_F)
{
curr_level = ftw->level;
if (pre_level != 0 && (count_file + count_dir != 0))
{
for (size_t i = 0; i < 9; i++)
{
printf("%c", Permissions[i]);
}
printf(" %s\t%s %15ld] %s\n", user_name, group_name, file_size, pre_name);
if ((count_dir + count_file) == count_total - 1)
{
for (size_t i = 0; i < 9; i++)
{
printf("%c", Permissions[i]);
}
printf(" %s\t%s %15ld] %s\n\n", user_name, group_name, file_size, pre_name);
}
}
if (type == FTW_D && strcmp(".", name) != 0)
count_dir++;
}
return 0;
}
int main(int argc, char const *argv[])
{
int flag = 0;
if (argc == 1)
{
nftw(".", tree_walk_counter, 10, flag);
nftw(".", tree_walk, 10, flag);
}
else if (argc == 2)
{
nftw(argv[1], tree_walk_counter, 10, flag);
nftw(argv[1], tree_walk, 10, flag);
}
else
{
fprintf(stderr, "write ./stree \"directory name\" or just ./stree\n");
exit(1);
}
char * dirs;
char * files;
if (count_dir == 1) dirs = "directory";
else dirs = "directories";
if (count_file == 1) files = "file";
else files = "files";
printf("%d %s, %d %s\n", count_dir, dirs, count_file, files);
return 0;
}
when i run with valgring:
==7132==
==7132== HEAP SUMMARY:
==7132== in use at exit: 1,158 bytes in 182 blocks
==7132== total heap usage: 369 allocs, 187 frees, 595,272 bytes allocated
==7132==
==7132== LEAK SUMMARY:
==7132== definitely lost: 1,137 bytes in 179 blocks
==7132== indirectly lost: 0 bytes in 0 blocks
==7132== possibly lost: 0 bytes in 0 blocks
==7132== still reachable: 21 bytes in 3 blocks
==7132== suppressed: 0 bytes in 0 blocks
==7132== Rerun with --leak-check=full to see details of leaked memory
==7132==
==7132== For lists of detected and suppressed errors, rerun with: -s
==7132== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Any advice? I tried to put free on the variables but it did segmentation fault