问题
I am brushing up my C skills from Learn C The Hard Way, currently I am at 17th Exercise.
I am doing the 'Extra Credits' part. Making the database code given on that page to get I am trying to
"Change the code to accept parameters for MAX_DATA and MAX_ROWS, store them in the Database struct, and write that to the file, thus creating a database that can be arbitrarily sized"
So, I commented out the #define directives, and changed Address and Database structs as given:
struct Address {
    int id;
    int set;
    char *name;
    char *email;
};
struct Database {
    int MAX_DATA;
    int MAX_ROWS;
    struct Address *rows;
};
So that, I can get MAX_DATA, and MAX_ROWS parameters from the user to create a database as per his liking. Other things I changed in the code are --
The Database_create function :
void Database_create(struct Connection *conn, int MAX_DATA, int MAX_ROWS)
{
        int i = 0;
        conn->db->MAX_DATA = MAX_DATA;
        conn->db->MAX_ROWS = MAX_ROWS;
        conn->db->rows = malloc(sizeof(struct Address) * MAX_ROWS);
        for(i = 0; i < MAX_ROWS; i++) {
                struct Address addr = {.id = i, .set = 0};
                conn->db->rows[i] = addr;
        }
}
The part where I am getting 'Invalid read of 4 bytes', and SegFault is :
void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
    struct Address *addr = &conn->db->rows[id];
    int MAX_DATA = conn->db->MAX_DATA;
    if(addr->set) die("Already set, delete it first");
    /* This if statement gives error for addr->set */
    addr->set = 1;
    addr->name = malloc(sizeof(char) * MAX_DATA);
    addr->email = malloc(sizeof(char) * MAX_DATA);
    // WARNING: bug, read the "How To Break It" and fix this
    char *res = strncpy(addr->name, name, MAX_DATA);
    // demonstrate the strncpy bug
    if(!res) die("Name copy failed");
    res = strncpy(addr->email, email, MAX_DATA);
    if(!res) die("Email copy failed");
}
I know this code snippets isn't the whole part, but I can't paste the whole code here. So, I've posted it here : http://pastebin.com/EbKShT3r I can create and write database for the first run using 'c' option. However, to add entries using 's' option, the Segmentation Fault occurs.
EDIT : So, Finally, I got this program working with the solution given under by @WhizCraig However, for freeing the memory, here is what I am trying :
void Database_close(struct Connection *conn)
{
    int i;
    if (conn) {
        int MAX_ROWS = conn->db->MAX_ROWS;
        for (i=0; i<MAX_ROWS; i++) {
            struct Address *row = conn->db->rows+i;
            if (row->set) {
                free(row->name);
                free(row->email);
            }
        }
        free(conn->db->rows);
        if(conn->file) fclose(conn->file);
        if(conn->db) free(conn->db);
        free(conn);
    }
}
And, I am getting errors in Valgrind, memory is leaking. I don't understand the error in above code. However, the main problem appears to be solved :)
回答1:
struct Address {
    int id;
    int set;
    char *name;
    char *email;
};
struct Database {
    int MAX_DATA;
    int MAX_ROWS;
    Address **rows; // USE ARRAY OF POINTERS
};
void Database_create(Connection *conn, int MAX_DATA, int MAX_ROWS)
{
        int i = 0;
        conn->db->MAX_DATA = MAX_DATA;
        conn->db->MAX_ROWS = MAX_ROWS;
        conn->db->rows = (Address**)malloc(sizeof(Address*) * MAX_ROWS);
        for(i = 0; i < MAX_ROWS; i++) {
                conn->db->rows[i] = (Address*)malloc(sizeof(Address));
                conn->db->rows[i]->id = i;
                conn->db->rows[i]->set = 0;
        }
}
void Database_set(Connection *conn, int id, const char *name, const char *email)
{
    if (!(conn && conn->db && conn->db->rows && conn->db->rows[id])) return;
    Address *addr = conn->db->rows[id];
    int MAX_DATA = conn->db->MAX_DATA;
    if(addr->set == 0) die("Already set, delete it first");
    addr->set = 1;
    addr->name = malloc(sizeof(char) * MAX_DATA);
    addr->email = malloc(sizeof(char) * MAX_DATA);
    char *res = strncpy(addr->name, name, MAX_DATA);
    if(!res) die("Name copy failed");
    res = strncpy(addr->email, email, MAX_DATA);
    if(!res) die("Email copy failed");
}
void Database_close(Connection *conn)
{
        size_t i;
        if(conn) {
                if (con->db && conn->db->rows) {
                        for (i = 0; i < conn->db->MAX_ROWS; i++) {
                                Address *cur = conn->db->rows[i];
                                free(cur);
                        }
                }
                if(conn->file) fclose(conn->file);
                if(conn->db) free(conn->db);
                free(conn);
        }
}
    回答2:
I modified the code Rohit posted here: http://pastebin.com/MvLXkDCz to fix the memory leaks. It runs through Valgrind without any errors. The relevant modifications are posted below:
void Database_close(Connection *conn)                                                 
{                                                                                     
  size_t i;                                                                           
  if(conn) {                                                                          
    if(conn->db && conn->db->rows) {                                                  
      for(i = 0; i < conn->db->max_rows; i++) {                                       
        Address *cur = conn->db->rows[i];                                             
        free(cur->name);                                                              
        free(cur->email);                                                             
        free(cur);                                                                    
      }                                                                               
      free(conn->db->rows);                                                           
    }                                                                                 
    if(conn->file) fclose(conn->file);                                                
    if(conn->db) free(conn->db);                                                      
    free(conn);                                                                       
  }                                                                                   
}   
void Database_delete(Connection *conn, int id)                                        
{                                                                                     
  conn->db->rows[id]->set = 0;                                                        
} 
You can find the complete program here:https://github.com/sookoor/Learn-C-the-Hard-Way/blob/master/ex17.c
来源:https://stackoverflow.com/questions/14950241/pointer-to-one-struct-in-another-writing-and-reading-it-from-file-gives-segfaul