segmentation fault in my c code

66 views Asked by At

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");

}

1

There are 1 answers

0
Jonathan Leffler On

You have:

int main(char *source)

This is a totally unorthodox and probably unsupported definition of main(). See What should main() 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:

DIR *dr;
…
dr = opendir(source);

You have actually got a (small but non-zero) int being treated as (part of?) a char *, which is going to lead to trouble.

You need:

int main(int argc, char **argv)
{
    if (argc != 2)
        …report error and do not continue…
    DIR *dr = diropen(argv[1]);
    …error check dr and continue if not null…