2013-09-24 38 views
0

我有這個功能,在那裏我得到數據庫的數據,我做了一個鏈表。列表中的每個節點都是一行。鏈接列表中的段錯誤

這是函數

Row * fetch(Query* query) 
{ 
    if (PQresultStatus(query->resultset) != PGRES_TUPLES_OK) 
     return NULL; 

    Row * row; 
    row = (Row *) malloc(sizeof (Row)); 

    row->total_cols = PQnfields(query->resultset); 
    int rows = PQntuples(query->resultset); 

    int row_atual, col_atual; 
    Row * aux; 
    aux = row; 

    for (row_atual = 0; row_atual < rows; row_atual++) { 
     for (col_atual = 0; col_atual < aux->total_cols; col_atual++) { 
      aux->cell[col_atual] = PQgetvalue(query->resultset, row_atual, col_atual); 
     } 
     aux->next_line = (Row *) malloc(sizeof(Row)); 
     aux = aux->next_line; 
    } 
    return row; 
} 

這是結構行:

typedef struct row { 
    int total_cols; 
    char ** cell; 
    struct row * next_line; 
} Row; 

問題是,當它達到這一點:

aux->next_line = (Row *) malloc(sizeof(Row)); 

我收到分段錯誤,我不知道爲什麼!我看不出有什麼問題。有人知道嗎?

謝謝!

+0

如果'row'變量不能是會發生什麼分配呢? – Mauren

+0

當我嘗試分配時,我收到一個段錯誤。但是,當我分配列表的第二個節點時發生了這種情況。 –

回答

2

您沒有爲組員分配內存,但你用它來存儲數據:

aux->cell[col_atual] = ...; 

的結果你在隨機地址破壞內存

+0

對不起,但我不明白... –

+0

你分配內存的aux-> next_line =(row *)malloc(sizeof(Row));但是aux-> cell呢? – AnatolyS

+0

那麼,我如何分配char **? –