char **a; 를 realloc() 하는것에서 어려움을 겪고 잇습니다.

jagalchee의 이미지

#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <sys/stat.h>
#include <unistd.h>

int main()
{
    DIR *directoryStream;
    struct dirent *directoryEntry;
    struct stat buf;
    char *fileName, **fileList;
    int len, fileCount=0, count;

    directoryStream = opendir("./");

    readdir(directoryStream);
    readdir(directoryStream);

    fileList = (char **)malloc(sizeof(char *));
    fileList[0] = (char *)malloc(1);

    while( (directoryEntry = readdir(directoryStream)) != NULL )
    {
        fileCount++;
        len = asprintf(&fileName, "./%s", directoryEntry->d_name);
        fileList = (char **)realloc(fileList, sizeof(char *)*fileCount);
#        fileList[fileCount-1] = (char *)realloc(fileList[fileCount-1], len);
    }
     
    return 0;
}

위의 코드는 특정 디렉토리에 속하는 파일 및 디렉토리 이름을 배열에다가 저장을 할려고 시도한 코드입니다. 특정 디렉토리에 존재하는 파일 및 디렉토리의 총 개수를 미리 한 큐에 알 수 잇는 방법을 찾지 못해서, readdir()로 한 번 읽을 때 마다 fileList 를 동적으로 한 칸씩 realloc() 해서 이름을 저장할려고 하는데, # 부분에서 세그폴이 뜨네요. 뭐가 문제인지 잘 몰라 질문드립니다.

그리고 전체 코드가 올바른 것인지도 궁금하구요.[/code]

cdpark의 이미지

#으로 표시한 줄은 realloc 대신에 malloc을 써야 하는 곳이군요. fileList[fileCount-1] 는 제대로 allocate된 공간이 아니니깐요.

그리고 매 entry를 추가할때마다 fileList 배열을 새로 realloc하는 건 효율성 면에서 "꽝"입니다. 좀 넉넉하게 할당하는 정책을 쓰는 게 좋겠죠. 보통 예전 크기의 2배 정도를 미리 잡는 정책이 널리 쓰입니다.

디렉토리의 파일 갯수는 seekdir과 telldir 함수로 알아낼 수 있습니다. 그리고 한번에 모든 디렉토리 내용을 다 읽어들이는 scandir이라는 함수도 있습니다. 자세한 내용은 RTFM!

alwaysrainy의 이미지

        fileList = (char **)realloc(fileList, sizeof(char *)*(fileCount+1));
        fileList[fileCount-1] = (char *)realloc(fileList[fileCount-1], len);
        fileList[fileCount] = (char *)malloc(1);

성능은 좀 떨어지겠지만.. 이런 코드라면 어찌되었던 간에 돌아갈 듯 하네요..
단, 결과물을 출력할때는 조금 신경을 써야 할 듯 ^^;

---------------------------------------
세계는 넓고, 할일은 많다.