【问题标题】:Segmentation fault, listing contents of a directory分段错误,列出目录的内容
【发布时间】:2015-07-06 23:15:16
【问题描述】:

我在 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

【问题讨论】:

  • 那是什么图书馆。我隐约记得以前看过它,但我需要一点记忆在那里慢跑。提及您正在使用的东西(标准库之外)总是一个好主意
  • 您要读取什么文件系统? ... ntfs 有几个陷阱?捷径?怪事?这样我就因为几个问题提前放弃了目录树。我也不认识你正在使用的库。我在 linux 上使用了
  • 您只对 8 种 d-types 中的 2 种采取了一些最小的操作...我建议您至少应该就检测到任何其他 d-types 发出警告,这可能是一个线索在那里。

标签: c++ c unix segmentation-fault


【解决方案1】:

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

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

应该是:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你能确定是哪一行出现了段错误吗?
    猜你喜欢
    • 2011-06-10
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2013-08-04
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多