链接列表中的Segfault

时间:2013-09-24 20:09:06

标签: c linked-list segmentation-fault

我有这个功能,我获取数据库的数据,我做了一个链表。列表的每个节点都是一行。

这是功能

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

我收到了分段错误,我不知道为什么!我看不出有什么不对。有人知道吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

您没有为单元成员分配内存,但是您使用它来存储数据:

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

因此会破坏随机地址的内存