Reputation: 1925
i've this function, where i get data of database and i make an linked list. Each node of the list is a row.
This is the function
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;
}
And this is struct row:
typedef struct row {
int total_cols;
char ** cell;
struct row * next_line;
} Row;
The problem is when it reaches this point:
aux->next_line = (Row *) malloc(sizeof(Row));
I received a segmentation fault, and i don't know why! I can't see what's wrong. Someone knows?
Thanks!
Upvotes: 0
Views: 69
Reputation: 4319
You did not allocate memory for the cell member but you use it to store data:
aux->cell[col_atual] = ...;
as the result you spoil memory at random addresses
Upvotes: 2