2013-03-14 25 views
0

出於某種原因,當我嘗試運行此測試代碼時,出現分段錯誤。該程序應該從文件中讀取字符串並將其放入數組中。我是C新手,嘗試使用調試器,但遇到問題。將字符串從文件讀入數組

任何輸入將不勝感激。

void fillArray(char *array[], int * count, FILE * fpin){  

char buf[40]; 
char *p; 
count = 0; 
while(fgets(buf, 40, fpin) != NULL){ 
    if((p= strchr(buf, '\n')) != NULL) 
    *p = '\0'; //step on the '\n' 
    array[(*count)++] = malloc(strlen(buf)+1); 
    assert(array[*count]); 
    strcpy(array[*count], buf); 
    (*count)++; 
} 
} 
+3

它做什麼,而不是你認爲它應該做什麼? [除了'count = 0'的明顯錯字應該是'* count = 0',那就是?] – 2013-03-14 20:53:54

+0

另外,還有一個語義錯誤:你正在增加'* count'兩次。 – 2013-03-14 20:54:25

+0

我已經修復了這個錯字,貼錯了,對不起。無論如何,現在的代碼在試圖在測試文件中運行時會出現分段錯誤錯誤。 – silentman45 2013-03-14 20:57:21

回答

1
array[(*count)++] = malloc(strlen(buf)+1); 
       ^^^ 
assert(array[*count]); 

首先,遞增,然後使用在陣列中的下一個位置,大概是未初始化的指針。從該行刪除++

+1

我喜歡這些'clang'式的錯誤放置標記'在這裏^^^'。 – 2013-03-14 20:55:00

+0

@ H2CO3 :-))所以我 – cnicutar 2013-03-14 20:55:23

+0

我修正了在代碼中。但是我仍然遇到分段錯誤。它可能是我的測試儀類主要方法中的東西? – silentman45 2013-03-14 21:05:19

0

希望這會有所幫助。該函數自動管理陣列和陣列條目的內存。

void fillArray(char ***array, int *count, FILE *fpin) 
{ 
    char *tmp[] = 0; 
    int tmp_allocated = 0; 
    int tmp_count = 0; 

    assert(array); 
    assert(count); 
    assert(fpin); 

    while(fgets(buf, 40, fpin) != NULL) 
    { 
     if ((p= strchr(buf, '\n')) != NULL) 
     { 
      *p = 0; 
     } 
     if (tmp_count == tmp_allocated) 
     { 
      tmp_allocated += 10; 
      tmp = realloc(tmp, sizeof(char*) * tmp_allocated); 
      assert(tmp); 
     } 
     tmp[tmp_count] = strdup(buf); 
     assert(tmp[tmp_count]); 
     tmp_count++; 
    } 

    *array = realloc(tmp, sizeof(char*) * tmp_count); 
    *count = tmp_count; 
} 

在這裏,我們如何使用它。

void userOfFillArray() 
{ 
    int count; 
    char **array; 
    FILE *fpin = ...; 

    fillArray(&array, &count, fpin); 
    // if count == 0, then array can be NULL 

    ... 

    while (count--) 
    { 
     free(array[count]); 
    } 
    free(array); 
}