简体   繁体   English

释放内存时出现分段错误

[英]segmentation fault while freeing memory

Here is a program I made this program has segmentation fault I checked it in gdb in the second last of code free(somepath); 这是我使该程序具有分段错误的程序,我在free(somepath);倒数第二个代码中在gdb中对其进行了检查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? 我该怎么做才能摆脱它?

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). 在代码中,不能保证分配内存并将其分配给somepath (除了循环的最后一次迭代,您还无法释放somepath)。 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. 您应该将free(somepath)语句放在for循环的末尾,并且应该在函数的开头和每个for循环的开始处都将somepath初始化为NULL,以避免类似的粗心错误。

You're not initializing the somepath variable - it has an undefined value unless the malloc() executes (ie for empty folders). 您没有初始化somepath变量-它具有未定义的值,除非malloc()执行(例如,用于空文件夹)。 You should initialize it to NULL at the place of definition. 您应该在定义位置将其初始化为NULL。

You do not initialize somepath to 0 (NULL), but you could under some circumstances release the value. 您无需将somepath初始化为0(NULL),但是在某些情况下可以释放该值。 This means you release a random value - which is not a good idea. 这意味着您释放一个随机值-这不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM