c - Initializing a nested structure -
this problem learn c hardway. database management system in c have 3 structures :-
struct address { int id; int set; char *name; char *email; }; struct database { int rows; struct address *row; }; struct connection { file *file; struct database *db; };
i trying initialize database structure. getting segfault
void database_create(struct connection *conn, int no_of_rows) { int = 0; conn->db->row_num = no_of_rows; for(i = 0; < conn->db->row_num; i++) { // make prototype initialize struct address addr; addr.id = i; addr.set = 0; // assign conn->db->rows[i] = addr; } }
i've made function allocates memory these structures.
struct connection *database_open(const char *filename, char mode) { struct connection *conn = malloc(sizeof(struct connection)); if(!conn) die("memory error"); int number = conn->db->rows; conn->db = malloc(sizeof(struct database)); if(!conn->db) die("memory error"); conn->db->row = malloc(sizeof(*conn->db->row) * number); if(!conn->db->row) die("memory error"); if(mode == 'c') { conn->file = fopen(filename, "w"); } else { conn->file = fopen(filename, "r+"); if(conn->file) { database_load(conn); } } if(!conn->file) die("failed open file"); return conn; }
valgrind says "use of uninitialized value of size 4" in database_open()
could suggest might doing wrong here?
db
in connection
, row
in database
uninitialised pointers. need initialise them , provide storage structs point to.
you can save dynamic allocation changing connection
have database
member rather pointer
struct connection { file *file; struct database db; };
you need allocate memory database rows
conn->db.row = malloc(no_of_rows * sizeof(*conn->db.row));
database_create
like
int database_create(struct connection *conn, int no_of_rows) { int = 0; conn->db.rows = no_of_rows; conn->db.row = malloc(no_of_rows * sizeof(*conn->db.row)); if (conn->db.row == null) { /* out of memory */ return 1; /* indicate failure caller */ } for(i = 0; < conn->db->rows; i++) { conn->db.row[i].id = i; conn->db.row[i].set = 0; } return 0; /* indicate success caller */ }
note assumes memory allocated connection
Comments
Post a Comment