이것은 어려운 부분을 배우면 문제가됩니다.중첩 구조 초기화
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
int rows;
struct Address *row;
};
struct Connection {
FILE *file;
struct Database *db;
};
나는 데이터베이스 구조를 초기화하는 -이 내가 세 가지 구조가 C 의 데이터베이스 관리 시스템입니다. 그러나 나는 segfault를 얻고있다.
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의 초기화되지 않은 값의 사용"()
사람이 내가 잘못 여기 일을 할 수있는 무엇을 제안 할 수 있을까요?
''int' 일 때 왜'rows'를 배열로 사용하고 있습니까? – tay10r
디버거를 사용하여 segfault의 원인을 확인하십시오. 가장 가능성있는'conn-> db'는 초기화되지 않았거나 뭔가가 없습니다. –
@Ajit'Database_create'를 호출하는 방법을 포함해야합니다. – tay10r