分段错误,列出目录的内容

时间:2015-07-06 23:15:16

标签: c++ c unix segmentation-fault

我在while循环结束时遇到分段错误(我不确定在终止之后或之前是否出现错误)。 我检查过dirlist_next_entry成功返回DIRLIST_END之后 到达目录流的末尾。我不明白导致故障的原因,因为在到达流结束后循环应该成功终止

#include "DirEntry.h"
#include <cstdio>

int main(int argc, char* argv[]){
    if(argc != 2){
        printf("Directory not specified\n");
        return -1;
    }
    DirListError error;
    DirEntry result;
    handle hfile = dirlist_start_find(argv[1], &error);
    while( dirlist_next_entry(hfile, &result) != DIRLIST_END){
        printf("%s  %lld\n", result.entry, result.size);
    }
    dirlist_end_find(hfile);

}

以下是dirlist_next_entry的定义:

DirListError dirlist_next_entry(handle h, DirEntry* result){
    DIR* dirp = (DIR*)h; 
    dirent* dr;
    if((dr = readdir(dirp)) == NULL){
        return DIRLIST_END;
    }

        strcpy(result->entry, dr->d_name);
    if(dr->d_type == DT_DIR){
        result->is_directory = 1;
    }
    else if(dr->d_type == DT_REG){
        result->is_directory = 0;
        struct stat* buf;
        stat(result->entry, buf);
        result->size = buf->st_size;
    } 

    return DIRLIST_OK;  
}

Direntry.h只是一个带有几个声明的标题:

#ifndef  DIRENTRY_H
#define DIRENTRY_H

const int MAX_PATH_LENGTH = 1024;
typedef void* handle;

struct DirEntry{
    char entry[MAX_PATH_LENGTH + 1];
    int is_directory;
    long long size;
};

enum DirListError{
    DIRLIST_OK,
    DIRECTORY_NOT_FOUND,
    INCORRECT_DIRECTORY_NAME,
    DIRLIST_END,
};

handle dirlist_start_find(const char* dir, DirListError* error);
DirListError dirlist_next_entry(handle h, DirEntry* result);
void dirlist_end_find(handle h);
#endif

2 个答案:

答案 0 :(得分:2)

我相信dirent *的d_name字段不是以null结尾。因此strcpy()可能会在以后导致分段错误。如果是这种情况,您应该使用strncpy()

答案 1 :(得分:2)

这很可能会覆盖随机存储器:

struct stat* buf;
stat(result->entry, buf);

应该是:

struct stat buf;
stat(result->entry, &buf);