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
",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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…