Search code examples
csegmentation-faultpointer-arithmetic

Pointer access beyond allocated memory does'nt cause segfault


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)

Solution

  • 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.