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

Segmentation fault, listing contents of a directory

我在 while 循环结束时遇到分段错误(我不确定错误是在终止之后还是之前出现)。 我已经检查 dirlist_next_entry 成功 returns 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 只是一个带有几个声明的 header:

#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

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

这很可能是覆盖随机内存:

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

应该是:

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