-3

I'm teaching myself C, and I do not understand why the following code do not break with a segmentation fault.

printf("loading \n");
conn->db = malloc(sizeof(struct Database));
int rc = fread(&conn->db->max_rows,sizeof(int) , 1, conn->file);
rc = fread(&conn->db->max_data,sizeof(int) , 1, conn->file);
conn->db->rows = malloc(Get_address_size(conn) * conn->db->max_rows);
printf("address size is : %d\n", Get_address_size(conn));
int i;
struct Address * r = conn->db->rows;
for (i = 0; i < conn->db->max_rows; i++)
{
    rc = fread(&r->id, sizeof(int) , 1, conn->file);
    rc = fread(&r->set, sizeof(int) , 1, conn->file);
    r->name = malloc(conn->db->max_data);
    r->email = malloc(conn->db->max_data);
    rc = fread(r->name, conn->db->max_data , 1, conn->file);
    rc = fread(r->email, conn->db->max_data , 1, conn->file);
    r = r++;
}
r=r+100;
printf(here I'm trying to break my code %d\n",r->id);
if (rc != 1) die("Failed to load database.");

the Get_address_size function is just a wrapper around

 sizeof(struct Address)
tumasgiu
  • 325
  • 3
  • 11
  • What is going on here `if (rc != ) die("Failed to load database.");`? – Ed Heal Mar 05 '16 at 10:01
  • 5
    Possible duplicate of [Why don't I get a segmentation fault when I write beyond the end of an array?](http://stackoverflow.com/questions/12410016/why-dont-i-get-a-segmentation-fault-when-i-write-beyond-the-end-of-an-array) – Martin James Mar 05 '16 at 10:03
  • @EdHeal, it just spit out a message andexit the program with 1 (It should also free allocated memory). – tumasgiu Mar 05 '16 at 10:05

1 Answers1

1

When program starts, OS will divide the programs memory into readable (code section) and writable (data section as well as heap). Now it will depend on the address stored in the pointer you are dereferencing. If it points to a valid writable memory then no segmentation fault exception will be raised, otherwise a segmentation fault exception will be raised.

0x0001
  • 525
  • 4
  • 12