Hello,
I have structs that are being saved to disk but when I try to access the pointers in the struct, it causes a seg fault:
Code:
struct Address {
int id;
int set;
char *name;
};
struct Connection *open_database(const char *filename, char mode) {
struct Connection *conn = malloc(sizeof(struct Connection));
if (!conn) {
die("Memory error");
}
conn->db = malloc(sizeof(struct Database));
if (mode == 'c') {
conn->file = fopen(filename, "w");
} else {
conn->file = fopen(filename, "r+");
if (conn->file) {
load_database(conn);
}
}
if (!conn->file) {
die("Failed to open the file");
}
return conn;
}
void load_database(struct Connection *conn) {
int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
if (rc != 1) {
die("Failed to load database.");
}
}
void create_database(struct Connection *conn) {
int i = 0;
for (i = 0; i < MAX_ROWS; i++) {
//initial values
struct Address addr = {.id = i, .set = 0};
addr.name = malloc(sizeof(char*));
conn->db->rows[i] = addr;
}
}
void set_database(struct Connection *conn, int id, const char *name) {
struct Address *addr = &conn->db->rows[id];
if (addr->set) {
die("Already set, delete it first");
}
addr->set = 1;
addr->name = strdup(name);
}
void write_database(struct Connection *conn) {
rewind(conn->file);
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
if (rc != 1) {
die("Failed to write database.");
}
rc = fflush(conn->file);
if (rc == -1) {
die("Cannot flush database.");
}
}
void list_database(struct Connection *conn) {
int i = 0 ;
struct Database *db = conn->db;
for (i = 0; i < MAX_ROWS; i++) {
struct Address *cur = &db->rows[i];
if (cur->set) {
print_address(cur);
}
}
}
void print_address(struct Address *addr) {
printf("%d %s\n", addr->id, addr->name);
}
The flow is as follows:
open connection => create_database =>write_database =>set_database =>write_database => list_database
The seg fault happens in when list_database() calls print_address. The code works if I change struct Address pointer *name to be char name[512] (size irrelevant here).
I've been stuck trying to figure out why it causes when I'm allocating space for a char*.
Thanks