Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3600688
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T20:31:37+00:00 2026-05-18T20:31:37+00:00

Here is a program I made this program has segmentation fault I checked it

  • 0

Here is a program I made this program has segmentation fault I checked it in gdb in the second last of code free(somepath); .I do not have any reason for why is this segmentation fault coming?
Some one please suggest some thing.

#include<dirent.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<stdio.h>
char *directs[20], *files[20];
int i = 0;
int j = 0;
int count = 0;

void printdir(char *);
int count_dirs(char *);
int count_files(char *);
void new_printdir(int ,int ,char *);
int main()
{
    char startdir[20];
    printf("Scanning user directories\n");
    scanf("%s", startdir);
    printdir(startdir);
}

void printdir(char *dir)
{


    DIR *dp = opendir(dir);
    int nDirs, nFiles, nD, nF;

    nDirs = 0;
    nFiles = 0;
    nD = 0;
    nF = 0;
    if (dp) {
        struct dirent *entry = 0;
        struct stat statBuf;

        nDirs = count_dirs(dir);
        nFiles = count_files(dir);



  new_printdir(nDirs,nFiles,dir);


        while ((entry = readdir(dp)) != 0) {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }

    char *     filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2);
            if (filepath) {
                sprintf(filepath, "%s/%s", dir, entry->d_name);
                if (lstat(filepath, &statBuf) == 0) {
                    if (S_ISDIR(statBuf.st_mode)) {
                    printdir(filepath);
                        }
                    else {
                    }
                }

            }    

            free(filepath);
        }        //2nd while

        closedir(dp);
    }

    else {
        fprintf(stderr, "Error, cannot open directory %s\n", dir);
    }

}                //printdir

int count_dirs(char *dir)
{
    DIR *dp = opendir(dir);
    int nD;
    nD = 0;
    if (dp) {
        struct dirent *entry = 0;
        struct stat statBuf;

        while ((entry = readdir(dp)) != 0) {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }

            char *filepath =  malloc(strlen(dir) + strlen(entry->d_name) + 2);

            if (filepath) {
                sprintf(filepath, "%s/%s", dir, entry->d_name);

                if (lstat(filepath, &statBuf) != 0) {
                    fprintf(stderr, "File Not found? %s\n",filepath);
                }

                if (S_ISDIR(statBuf.st_mode)) {
                    nD++;

                } else {
                    continue;
                }

                free(filepath);
            }
        }

        closedir(dp);
    } else {
        fprintf(stderr, "Error, cannot open directory %s\n", dir);
    }
    return nD;
}

int count_files(char *dir)
{
    DIR *dp = opendir(dir);
    int nF;
    nF = 0;
    if (dp) {
        struct dirent *entry = 0;
        struct stat statBuf;

        while ((entry = readdir(dp)) != 0) {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }

            char *filepath =
                malloc(strlen(dir) + strlen(entry->d_name) + 2);

            if (filepath) {
                sprintf(filepath, "%s/%s", dir, entry->d_name);

                if (lstat(filepath, &statBuf) != 0) {
                    fprintf(stderr, "File Not found? %s\n",    filepath);
                }

                if (S_ISDIR(statBuf.st_mode)) {

                    continue;
                } else {
                    nF++;

                }

                free(filepath);
            }
        }

        closedir(dp);
    } else {
        fprintf(stderr, "Error, cannot open file %s\n", dir);
    }
    return nF;
}

void new_printdir(int nDirs,int nFiles,char *dir)
{

      struct dirent **namelist;
        DIR *dop;
        int i, j,t,re,nD,nF;

        char userd[20],*somepath;

       i = scandir(dir, &namelist, 0, alphasort);
        t=0;

        if (i < 0)
                perror ("Scandir failed to open directory I hope you understand \n");
        else {
                for (j = 0; j < i; j++) {
                if(strcmp(".",namelist[j]->d_name)==0||strcmp("..",namelist[j]->d_name)==0)
                continue;
              somepath = malloc(strlen(dir)+strlen(namelist[j]->d_name)+2);
                  sprintf(somepath,"%s/%s",dir,namelist[j]->d_name);
                        dop=opendir(somepath);

                        if(dop)
                         {

                nD++;
                            if ((nDirs-nD)<3)    
                        {printf("%s ",namelist[j]->d_name);}
                          }
                     else {
                nF++;
                if ((nFiles-nF)<3)    
                printf("%s ",namelist[j]->d_name);
              }
            closedir(dop);
                        free(namelist[j]);
                }
        }
        free(namelist);
 free(somepath);

}

Why is this segmentation fault happening this is not clear to me.
What can I do to get rid of it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T20:31:37+00:00Added an answer on May 18, 2026 at 8:31 pm

    In your code, you are not guaranteed to allocate memory and assign it to somepath (you also fail to free somepath except for the last iteration of the loop). You should put your free(somepath) statement at the end of the for-loop, and you should initialize somepath to NULL both at the very beginning of the function and at the start of each for loop to avoid similar careless errors.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: C programming, why does this large array declaration produce a segmentation fault?
I have a program i frequently use that is made with .NET. This program
I have a program here: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ipc.h> #include
I've got a Schroedinger's Cat type of problem here -- my program (actually the
Okay here's the program I have typed up(stdio.h is included also): /* function main
Here is a quick test program: public static void main( String[] args ) {
Here is a little test program: #include <iostream> class Test { public: static void
Here's a short test program: sub foo($;@) { my $sql = shift; my @params
Here's the purpose of my console program: Make a web request > Save results
Newbie here...can I write one program which incorporates .NET LINQ and also various Java

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.