这是艰苦学习C的问题。这是C语言中的数据库管理系统
我有三个结构:
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
int rows;
struct Address *row;
};
struct Connection {
FILE *file;
struct Database *db;
};
我试图初始化数据库结构。但是我遇到了段错误
void Database_create(struct Connection *conn, int no_of_rows)
{
int i = 0;
conn->db->row_num = no_of_rows;
for(i = 0; i < conn->db->row_num; i++) {
// make a prototype to initialize it
struct Address addr;
addr.id = i;
addr.set = 0;
// then just assign it
conn->db->rows[i] = addr;
}
}
我做了另一个将内存分配给这些结构的函数。
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 to open the file");
return conn;
}
valgrind在Database_open()中说“使用大小为4的未初始化值”
有人可以建议我在这里做错什么吗?
最佳答案
db
中的Connection
和row
中的Database
是未初始化的指针。您需要初始化它们,并为它们指向的结构提供存储。
您可以通过更改Connection
使其Database
作为成员而不是指针来保存一些动态分配。
struct Connection {
FILE *file;
struct Database db;
};
您需要为数据库行分配内存
conn->db.row = malloc(no_of_rows * sizeof(*conn->db.row));
Database_create
然后看起来像int Database_create(struct Connection *conn, int no_of_rows)
{
int i = 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 to caller */
}
for(i = 0; i < conn->db->rows; i++) {
conn->db.row[i].id = i;
conn->db.row[i].set = 0;
}
return 0; /* indicate success to caller */
}
请注意,这假设已经为
Connection
分配了内存