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);

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

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

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.