mercredi 18 mars 2015

Why is it that we can write outside of bounds in C?


I recently finished reading about virtual memory and I have a question about how malloc works within the Virtual address space and Physical Memory.


For example (code copied from another SO post)



void main(){
int *p;
p=malloc(sizeof(int));
p[500]=999999;
printf("p[0]=%d\n",p[500]); //works just fine.
}


Why is this allowed to happen? Or like why is that address at p[500] even writable?


Here is my guess.


When malloc is called, perhaps the OS decides to give the process an entire page. I will just assume that each page is worth 4KB of space. Is that entire thing marked as writable? That's why you can go as far as 500*sizeof(int) into the page (assuming 32bit system where int is size of 4 bytes).


I see that when I try to edit at a larger value...



p[500000]=999999; // EXC_BAD_ACCESS according to XCode


Seg fault.


If so, then does that mean that there are pages that are dedicated to your code/instructions/text segments and marked as unwrite-able completely separate from your pages where your stack/variables are in (where things do change) and marked as writable? Of course, the process thinks they're next to each order in the 4gb address space on a 32-bit system.




Aucun commentaire:

Enregistrer un commentaire