I'm attempting to learn C using http://c.learncodethehardway.org/ but I'm stuck on one of the extra credit questions in chapter 18 (http://c.learncodethehardway.org/book/learn-c-the-hard-waych18.html) and I'm hoping someone can help me.
The specific problem I'm having is there are a couple of structs defined like this:
#define MAX_ROWS = 500;
#define MAX_DATA = 512;
struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
};
struct Database {
struct Address rows[MAX_ROWS];
};
struct Connection {
FILE *file;
struct Database *db;
};
The challenge is to rework that so that rows
can have a variable size that doesn't rely on that constant.
So in my Database_create method I'm attempting to initialize rows
with the following:
conn->db->rows = (struct Address*) malloc(max_rows * sizeof(struct Address));
where conn->db
points to an instance of Database and max_rows
is an int that gets passed to the function.
I've also changed the Database struct to
struct Database{
struct Address* rows;
}
That bit of code seems to run ok but if I try and access any member of rows
I get a segmentation fault which I believe means I'm attempting to access bits of memory that aren't in use.
I've spent a good few hours on this and I'm sure I can't be too far off but I'd really appreciate any guidance to get me on the right track.
EDIT: Just wanted to add some more detail to this after running it with Valgrind, that throws up the error:
==11972== Invalid read of size 4
==11972== at 0x100001578: Database_set (ex18.c:107)
==11972== by 0x100001A2F: main (ex18.c:175)
==11972== Address 0x7febac00140c is not stack'd, malloc'd or (recently) free'd
The line of code it's point to is:
struct Address *addr = &conn->db->rows[id];
if(addr->set) die("Already set, delete it first");
Line 107 is the if(addr->set)
which I presume means it's trying to read something it can't