I am getting segmentation fault in my code what is the reason for that.
I think this is because of while loop in cur = readdir(dr); it is not entering into while loop when I am trying to give wrong entry.
int main(char *source)
{
DIR *dr;
struct dirent *cur;
struct stat fi;
long int total_size = 0;
dr = opendir(source);
char *name=source;
size_t sourcelen = strlen(source);
printf("\n\n Source is %s\n\n\n", source);
printf("before *path \n");
char *path = malloc(100);
strcpy(path,source);
printf("before while \n");
while ((cur = readdir(dr)) != NULL)
{
if(cur->d_name[0] != '.')
{
free(path);
path = malloc(sourcelen + strlen(cur->d_name) + 2);
strcat(path,source);
strcat(path,"/");
strcat(path,cur->d_name);
if(stat(path, &fi) == -1)
{
printf("error \n\n");
}
else
{
printf("%s ",cur->d_name);
printf("%ld ",fi.st_blocks);
total_size = total_size + fi.st_blocks;
}
}
}
printf("\n\ntotal_size = %ld \n", total_size);
printf("\n\n\n");
}
You have:
This is a totally unorthodox and probably unsupported definition of
main()
. See What shouldmain()
return in C and C++ for the full story of what is and is not allowed.It is almost certainly the cause of your segmentation fault too. You have:
You have actually got a (small but non-zero)
int
being treated as (part of?) achar *
, which is going to lead to trouble.You need: